MVC 4 models not accept jquery datapicker date format c# entity-framework-6 jquery-ui-datepicker


I am using Entity framwork 6 , MVC 4 and jquery datepicker. When fill all the form data and press the submit button the ModelState.IsValid always return false value, because the jquery datepicker value not match with the model validation field.

in .cshtml file

@Html.TextBoxFor(m => m.Annieversary, new { id = "anudate", @class = "form-control datetimepicker", @placeholder = "Annieversary Date" })

c# Side

    [Required(ErrorMessage = "This field is required")]

    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    [DataType(DataType.Date, ErrorMessage = "Date required")]
    public Nullable<System.DateTime> Annieversary { get; set; }

I tried below

@Html.TextBoxFor(m => m.Annieversary,"{0:dd/MM/yyyy}", new { id = "anudate", @class = "form-control datetimepicker", @placeholder = "Annieversary" })

This is also not match with the model, always return null value. I know c# only accept the "MM/DD/YYYY" format but jquery datepicker return "DD/MM/YYYY" format. How can I solve this problem?

12/19/2016 6:30:31 AM

Popular Answer

First of all, let's simplify so it can work. Then you can add the attributes you feel you need.

Notice that I am using the question mark to make the field nullable - as I understand you will need it:

public DateTime? Anniversary { get; set; }

Notice the datepicker class, which we will use to call the jQuery UI DatePicker component:

@Html.TextBoxFor(m => m.Anniversary, new { @class = "datepicker" })

Notice that I am setting the dateFormat to the format you need. That helps but it's not enough just yet:

$(function () {
    $(".datepicker").datepicker({ dateFormat: "dd/mm/yy" });

Now, here is where the magic happens. You need to set the culture of your application in order to have the proper date format. I have it set to pt-BR, which gives the same date format you need:

<globalization culture="pt-BR" uiCulture="pt-BR"/>

That should do it, but it's the most basic example.

The most important thing to remember is: The date format should always match the culture you set in the web.config.

12/19/2016 10:10:25 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow