Search code examples
asp.net-mvcasp.net-mvc-5jquery-ui-datepickerunobtrusive-validation

MVC binding back incorrect date format


I am using Jquery datepicker as follows:-

$(".jqueryui-marker-datepicker").datepicker({
    dateFormat: "mm/dd/yy",
    yearRange: "-100:+0",
    changeYear: true,
    changeMonth: true,
    showOn: "button"
}).css("display", "inline-block").next("button").button({
    icons: { primary: "ui-icon-calendar" },
    label: "Select A Date",
    text: false
});

Following is the editor template:-

@model DateTime?
@Html.TextBoxFor(model => Model,"{0:dd-MM-yyyy}",new { @class = "form-control jqueryui-marker-datepicker" });

Now i have datetime? column in my model

    [Display(Name = "Date of birth")]
    [DataType(DataType.Date)]
    [Required(ErrorMessage = "DATEDOB is required")]
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? DATEDOB { get; set; }

and create and edit view has following

 <div class=" col-md-3">
      @Html.EditorFor(model => model.DATEDOB, "{0:MM/dd/yyyy}", new { htmlAttributes = new { @class = "datepicker" } })
      @Html.ValidationMessageFor(model => model.DATEDOB, "", new { @class = "text-danger" })
 </div>

When create it date goes into table correctly

4/21/2000 12:00:00 AM

However when edit view comes up it shows it as

21-04-2000.

earlier it was giving an jquery validation error that this is not a modal date. I have resolved that.

So now when i click on Submit button,it gives me an error that "the value is not a valid date"

I have "en-US" as cuture and Uiculture. I currently running the web app at my local machine in india.

I am not sure how to go about.Any suggestions?


Solution

  • Your editor template use different format for date, try changing this code

    @model DateTime?
    @Html.TextBoxFor(model => Model,"{0:MM/dd/yyyy}",new { @class = "form-control jqueryui-marker-datepicker" });