MVC3 + Datepicker + UK Date

2019-08-20 13:33发布

问题:

Dudes, been trying for very long time on solving this. I have been looking around and been fiddling around but i just cant get it to work!!

For my DOB, im hoping to accept date in dd/mm/yyyy.. however it only accepts mm/dd/yyyy. Where should i make the fix?

I got inspirations from Jquery Datepicker 1 and Jquery Datepicker 2.

In my Model

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Date of Birth")]
public DateTime DOB { get; set; }

In my View, pretty straight forward

@Html.EditorFor(model => model.DOB)

Have an Editor Template that is called up whenever date is used.

@model DateTime?

@Html.TextBox("", Model != null ? Model.Value.ToString("dd/mm/yyyy") : "", new { @class   = "date" })

Wrote another editorhookup, that refs Jquery

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

Any help is appreciated!

回答1:

Where should i make the fix?

In your editor template:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "date" })

That's for displaying the date in the correct format.

For binding the value back in a POST controller action you could write a custom model binder that will use the [DisplayFormat] attribute to parse the value back to a valid DateTime instance using the specified format.