Populating HTML5 Datepicker With Data Passed From

2019-09-03 08:19发布

问题:

I'm working on making a basic scheduling application for a project. We've implemented a simple DateTime picker to ease the process of selecting a start and end time/date for our events. The source code for this is:

<input type="datetime-local" name="starttime" id="field1" />

The ending time calendar is the same barring the name. This works perfectly fine for taking in dates and time for events and we're quite happy with it. The issue is that when going to edit an entry the calendar does not populate with data from the model as other elements in the view do. Other elements within the view are using HTML helpers generated by scaffolding the project, so no problems there. We'd use the default option for the DateTimes, but textbox inputs for this aren't considered user friendly enough to implement.

I've done some looking around and it seems that the value of the calenders can be set using "value =". Razor syntax seems to be the likely choice, but I have no frame of reference due to other elements being handled by Html helpers. Can anyone clarify on how best to approach this issue? I've included our editing portion of the associated controller for reference.

 public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Request request = db.Requests.Find(id);
        if (request == null)
        {
            return HttpNotFound();
        }
        ViewBag.AccountId = new SelectList(db.Accounts, "Id", "FirstName", request.AccountId);
        ViewBag.RoomId = new SelectList(db.Rooms, "Id", "Id", request.RoomId);
        return View(request);
    }

回答1:

You can use the standard helpers to render a HTML5 date picker (and you get the benefits of model binding and unobtrusive validation). Assuming your model has property public DateTime StartTime { get; set; }, then

@Html.TextBoxFor(m => m.StartTime, "{0:s}", new { @type = "datetime-local" })

or using the longhand format "{0:yyyy-MM-ddTHH:mm:ss}"



回答2:

The answer by Stephen will probably work best with your current setup, another way you could do this is to use JQuery + UI which will also give you a nicer GUI to work with. With JQ in place you now have a way to find the datepicker handle and modify the values. Some explanation here: https://code.msdn.microsoft.com/Using-the-jQuery-UI-e420f255