Wednesday, May 2, 2012

jQuery datepicker problem with control generated in loop in asp.net MVC

Today I have faced a unique problem with datepicker while working in asp.net MVC.

I have added some textboxes using HTML.TextBoxFor inside a loop and then implemented datepicker on the textboxes. Part of the code goes like this-
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/redmond/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
    $(document).ready(function () {
        $("input[id*=DateTaken]").datepicker({
            dateFormat: "dd/mm/yy",
            changeMonth: true,
            changeYear: true
        });
    });
</script>

@for (int i = 0; i < 10; i++)
{
    @Html.TextBoxFor(m=> m.EventDate)
}
Now problem is that datepicker is enabled in all the textboxes, but on selection of date from the picker its adding the selected date to the first text box only. On digging further I can see the textboxes HTML got generated like below-
<input id="DateTaken" name="EventDate" type="text" value="" />
<input id="DateTaken" name="EventDate" type="text" value="" />
<input id="DateTaken" name="EventDate" type="text" value="" />
.
.
.
That is control got generated with same id and name 10 times. This is not a valid HTML. But suppose we need the control to be generated like this. Such control collection will be posted as an array with the name EventDate to the controller.

This can be solved very easily. Just generating different ID for each input control. That is the following code change will solve the problem-
@Html.TextBoxFor(m=> m.EventDate, new { @id = "DateTaken"+item.ToString() })

No comments:

Post a Comment