Reputation: 16719
I have several textbox elements being generated in a foreach, like this:
@foreach(var thing in Model.Things)
{
<tr>
<td>@Html.TextBoxFor(m => thing.StartDate, new { id = "thingStartDate", @class = "thingDatePicker" })</td>
</tr>
}
I'm attaching jQuery datepickers to each textbox, like this:
$(document).ready(function(){
$(".thingDatePicker").datepicker({ dateFormat: "mm/dd/yy" });
});
The datepickers all fire correctly on each textbox, in the correct positions. But when I select a date from any of them, it only populates the first textbox. How do I make sure each datepicker is firmly associated with its textbox?
Upvotes: 0
Views: 1694
Reputation: 1039318
You seem to be using the same id for all your textboxes (id="thingStartDate"
) which obviously results in invalid HTML. So either remove the id attribute or make sure you don't get dupes. I would probably remove it as you are using a class selector and this id serves no purpose at all:
@foreach(var thing in Model.Things)
{
<tr>
<td>
@Html.TextBoxFor(
m => thing.StartDate,
new { @class = "thingDatePicker" }
)
</td>
</tr>
}
Also I hope you realize that m => thing.StartDate
will generate incorrect names for those textboxes. It will use name="StartDate"
instead of name="Things[xxx].StartDate"
which might get you into troubles later when you attempt to bind back to your view model. For this purpose I recommend scraping the foreach
loops in view in favor of editor/display templates:
@Html.editorFor(x => x.Things)
and inside the corresponding editor template (~/Views/Shared/EditorTemplates/Thing.cshtml
)
@model Thing
<tr>
<td>
@Html.TextBoxFor(
x => x.StartDate,
new { @class = "thingDatePicker" }
)
</td>
</tr>
Upvotes: 2