Tag Archives: Controllers

ASP.NET MVC dates edit and display

Date formatting in ASP.NET MVC

In classic asp to display the date from the database we would open a record set and then call the field response.write rs(“datecreated”) if the server was set to UK localisation the result would be displayed as 13/07/2016.

ASP.NET is a bit different,

The model

[Display(Name = "Day created")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime Datecreated { get; set; }

using data annotations set the date format to yyyy-MM-dd as the default date picker can only display this format.  Dates in the database are in dd/MM/yyyy format.

Display name sets label of the box shown on screen. DataType changes the input box to type = Date. On modern browsers this enables a date picker.

The view
– Create

<div class="form-group">
@Html.LabelFor(model => model.Datecreated, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Datecreated, new { htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.ToString("yyyy-MM-dd") } })
@Html.ValidationMessageFor(model => model.Datecreated, "", new { @class = "text-danger" })

Setting a default value, we can pass the @Value attribute. Using html.EditorFor new htmlAttributes @Value = DateTime.Now.ToString(“yyyy-MM-dd”) must be in this format for the date box on the browser to display.

– index

As we have set the date format to yyyy-MM-dd in the model for display on editing we need to reformat the date on the index / any display page.

Entity frame work uses @Html.Displayfor but we want to change this to

@item.Datecreated.ToString("dd MMM yyy")

Assuming your for loop uses item. The above format displays like 14 Jul 2016