In my ASP.net MVC app I have a view that looks like this:
...
<label>Due Date</label>
<%=Html.TextBox("due")%>
...
I am using a ModelBinder
to bind the post to my model (the due property is of DateTime
type). The problem is when I put "01/01/2009" into the textbox, and the post does not validate (due to other data being input incorrectly). The binder repopulates it with the date and time "01/01/2009 00:00:00".
Is there any way to tell the binder to format the date correctly (i.e. ToShortDateString()
)?
Decorate the property in your model with the
DataType
attribute, and specify that its aDate
, and not aDateTime
:You do have to use
EditorFor
instead ofTextBoxFor
in the view as well:I found this question while searching for the answer myself. The solutions above did not work for me because my DateTime is nullable. Here's how I solved it with support for nullable DateTime objects.
MVC4 EF5 View I was trying to preload a field with today's date then pass it to the view for approval.
In the view, my first code allowed an edit:
Later I changed it to just display the date, the user cannot change it but the submit triggers the controller savechanges
When I changed to DisplayFor I needed to add this to ensure the preloaded value was passed back to the controller. I also need to add HiddenFor's for every field in the viewmodel.
Beginners stuff but it took a while to work this out.
Why don't you use
First, add this extension for getting property path:
Than add this extension for HtmlHelper:
Also you should add this jQuery code:
datepicker is a jQuery plugin.
And now you can use it:
ASP.NET MVC2 and DateTime Format
This worked for me: mvc 2
<%: Html.TextBoxFor(m => m.myDate, new { @value = Model.myDate.ToShortDateString()}) %>
Simple and sweet!
A comment of user82646, thought I'd make it more visible.