Search code examples
jqueryasp.net-mvcjquery-uimvc-editor-templates

MVC Editor Templates for Date Ranges using JQuery UI DatePicker


I need to display JQuery UI Datepicker on most of my MVC views. So I have created a Model class for Date Range:

public class DateRange
{
    [DisplayName("From")]
    [DataType(DataType.Date)]
    public DateTime? FromDate { get; set; }

    [DisplayName("To")]
    [DataType(DataType.Date)]
    public DateTime? ToDate { get; set; }
}

and an editor tamplate for it:

@model DateRange
@Html.LabelFor(model => model.FromDate)
@Html.TextBoxFor(model => model.FromDate, "{0:dd/MM/yyyy}", new { @class = "dateRangeFrom"})
@Html.LabelFor(model => model.ToDate)
@Html.TextBoxFor(model => model.ToDate, "{0:dd/MM/yyyy}", new { @class = "dateRangeTo"})

and on my EditorHookup.js file:

$(function ()
{
    $('.dateRangeFrom').datepicker({
        dateFormat: "dd/mm/yy",
        onClose: function (selectedDate) {
            $(".dateRangeTo").datepicker("option", "minDate", selectedDate);
        }
    });
    $('.dateRangeTo').datepicker({
        dateFormat: "dd/mm/yy",
        onClose: function (selectedDate) {
            $(".dateRangeFrom").datepicker("option", "maxDate", selectedDate);
        }
    });
})

This all works perfectly unless I need two of these date range models in my view. As you can predict, this doesn't work for multiple date ranges.

Edit: The problem for example is when I close the 'From' picker on the first date range, it will set the initial date of 'To' picker on BOTH date ranges.

Any help please?


Solution

  • One way to do this could be to put both textboxes in a <div>. So your new editor template :

    @model DateRange
    <div>
    @Html.LabelFor(model => model.FromDate)
    @Html.TextBoxFor(model => model.FromDate, "{0:dd/MM/yyyy}", new { @class = "dateRangeFrom"})
    @Html.LabelFor(model => model.ToDate)
    @Html.TextBoxFor(model => model.ToDate, "{0:dd/MM/yyyy}", new { @class = "dateRangeTo"})
    </div>
    

    And the js should look like this :

    $(function ()
    {
        $('.dateRangeFrom').datepicker({
            dateFormat: "dd/mm/yy",
            onClose: function (selectedDate) {
                $(this).closest("div").find(".dateRangeTo").datepicker("option", "minDate", selectedDate);
            }
        });
        $('.dateRangeTo').datepicker({
            dateFormat: "dd/mm/yy",
            onClose: function (selectedDate) {
                $(this).closest("div").find(".dateRangeFrom").datepicker("option", "maxDate", selectedDate);
            }
        });
    })
    

    *Untested code

    Hope it helps!