I'm running through the tutorials for ASP.NET MVC 4 (but I think this would also apply to MVC 5), in which you create a website for a movie store.
The movie model has a ReleaseDate property of type DateTime. Generally this date is going to be viewed more than it is edited, so I applied the following attributes to render it nicely.
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}")]
public DateTime ReleaseDate { get; set; }
When a view that displays this date renders it using:
@Html.DisplayFor(model => model.ReleaseDate)
it's displayed nicely formatted, as you'd expect:
But, when a view that edits this date renders it using:
@Html.EditorFor(model => model.ReleaseDate)
it displays a lovely HTML5 date picker, but doesn't fill in the value because the date's in the wrong format (error message is The specified value '11/01/1989 00:00:00' does not conform to the required format, 'yyyy-MM-dd'.
This is a problem, because if a user wants to edit an entry, the date from the control never gets set, so the user won't know what the previous/current value is.
A solution I've found from reading other similar questions is to set the DisplayFormat in the model to yyyy-MM-dd and make is applicable for edit controls:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime ReleaseDate { get; set; }
This works, in that it auto populates the value for the HTML5 date picker during editing (using @Html.EditorFor())
:
But I'm stuck with ugly ISO format dates for when I'm displaying (using `@Html.DisplayFor()):
My real question is: can I have different display formats for normal display and editing mode, set in the model?
@Html.DisplayFor
for displaying and @Html.EditorFor
for editing)What I'm trying to achieve is something like this:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] // use this format for edit controls
[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = false)] // use this format for display controls
public DateTime ReleaseDate { get; set; }
but you can't have two display format attributes for one property.
Use format parameter for method TextBoxFor and override the type attribute:
@Html.TextBoxFor(m => m.ReleaseDate, "{0:yyyy-MM-dd}", htmlAttributes: new { @type="date" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With