Search code examples
asp.net-mvcjquery-ui-datepicker

MVC bind jQuery datepicker to properity


first of all, please excuse my English. I am doing web application in MVC, and have a problem with binding jQuery datepicker to Model properities. If i bind the datepicker to Model properities (like a "test" in code below), everything works, but I have a Model that contains my own class, and that class contains a property which i need bind datepicker to and i dont know how...

ViewModel

public class MainViewModel
{
    //ViewModel 
    public Filtr Fil { get; set; }
    public DateTime test { get; set; }

}

Class in ViewModel

public class Filtr
{
    [Display(Name = "Date from:")]
    public DateTime? DatumFrom { get; set; }

    [Display(Name = "Date to:")]
    public DateTime? DatumTo { get; set; }
}

Part of Index.cshtml

@model aAKV.Models.MainViewModel 
.
.
.     
 <script>
    $(document).ready(function () {
        jQuery('#Fil.DateFrom').datetimepicker({
            lang: 'cs',
            formatDate: 'd.m.Y',
            formatTime: 'H:i',
            format: 'd.m.Y H:i',
            dayOfWeekStart: 1,
            step: 15,
            timepicker: true,
            mask: true
        });            

    });
</script>
}
@using (Html.BeginForm())
{

<div class="form-group">
    <div class="col-sm-3">

        @Html.LabelFor(Model => Model.Fil.DateFrom)
             @Html.TextBoxFor(model => model.Fil.DateFrom, new { @class = "date-picker" })
.
.
.

Thank you for any help


Solution

  • The reason your code isn't working is because @Html.TextBoxFor() creates an input with Fil_DateFrom as the id. Not Fil.DateFrom.

    You can try any of the options based on your requirement:

    1) You can change it to: $('#Fil_DateFrom').datetimepicker({

    2) But the above id might confuse some one else looking at your code and make them wonder where Fil_DateFrom is coming from. So you can assign a unique id to the input like this:

    @Html.TextBoxFor(model => model.Fil.DateFrom, new { id="date-from", @class ="date-picker"})
    

    And then in your script $('#date-from').datetimepicker({

    3) Another option, would be to target based on the class:

    $('.date-picker').datetimepicker({: This will add the datepicker to all the inputs on the page with date-picker class. This approach won't work if you want different settings to different datepickers.

    Let's say you want to disable weekends on your DateFrom datepicker, but allow weekends on DateTo datepicker. Then you'd have to assign unique ids to both inputs and follow the approach 2.