Consider the following Model:
public class ExportRequestsFilter {
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? StartDate { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? EndDate { get; set; }
...
With the respective View:
<script type="text/javascript">
$(document).ready(function () {
$(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' }); // this is the datepicker equivalent to dd/MM/yyyy
});
</script>
...
<% using (Html.BeginForm(FormMethod.Post)) {%>
...
<%: Html.TextBox("StartDate", Model.StartDate, new { @class = "datepicker" })%><br />
<%: Html.TextBox("EndDate", Model.EndDate, new { @class = "datepicker" })%>
<input type="submit" class="buttonLink" name="submitButton" value="<%: Html.Resource("Preview") %>" />
Is there any good reason for when the data on StartDate TextBox is 2/4/2012, UpdateModel() sets the StartDate to 4 February 2012 instead of 2 April 2012?
It depends on the culture settings for the computer doing the parsing of the input. So if the webserver is set to parse the
DateTimebased on en-US culture it will parse it asMM/dd/yyyyeven though the webpage is setup to render it asdd/MM/yyyy. If you want to force the parsing to always be of one format then you have to pass in the Culture information when you call DateTime.Parse inside a custom binder.EDIT: Actually I think this can be set in the web.config to use a default culture for the application. Having not worked with different culture settings though I don’t know for sure how to do this.
MSDN has a good article on globalizing ASP.NET applications that would work with MVC. Also this article on StackOverflow would explain how to do it with MVC in the web.config. If you follow the answer there it should automatically parse the DateTime in the format you are looking for.