I am trying to have two submission forms with similar functionality on the same view, where each form is strongly typed to the same model. I then am trying to add a datepicker to the same input on both forms, but I am unsure of how to do this. Here is my code:
@using (@Ajax.BeginForm(...
new { id = "editScheduleForm" }))
{
<div class="editor-label">
@Html.LabelFor(model => model.StartTime)
</div>
<div class="editor-field">
<input
@Html.EditorFor(model => model.StartTime)
@Html.ValidationMessageFor(model => model.StartTime)
</div>
}
…
@using (@Ajax.BeginForm(...
new { id = "addScheduleForm" }))
{
<div class="editor-label">
@Html.LabelFor(model => model.StartTime)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.StartTime)
@Html.ValidationMessageFor(model => model.StartTime)
</div>
}
Both of these forms are in their own strongly-typed partial views. I naturally tried simply adding the datepicker in jQuery to both partial views, like so:
$(function () {
$("#StartTime").datepicker();
});
But it unsurprisingly only worked for one of the inputs. I have been trying to use the HTML id that I added to both Ajax form declarations (e.g. editScheduleForm and addScheduleForm), but am unsure of how to do this. Any suggestions?
Solution:
As scottm suggested, I looked through documentation for using a custom editor template. I read this, detailing functionality I didn’t know existed:
http://msdn.microsoft.com/en-us/library/ee407399.aspx
Here, you can specify a template, and then add a parameter for the htmlFieldName, which is specifically designed to circumvent the problem I was happening.
You can add a class to the inputs in your editor template. Then you can then use the class as the jQuery selector.
Add a file called
DateTime.cshtmlunder~/Views/Shared/EditorTemplates, and add the following:Then add this jQuery to the page.