Search code examples
c#asp.net-mvcformat-string

Using Data annotation in Model for DateTime


I am using following code to popup calendar for date in my razor view

Model

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
        [DataType(DataType.Date)]
        public Nullable<System.DateTime> EndTime { get; set; }

View

<div class="form-group">
            @Html.LabelFor(model => model.EndTime, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-4">
                @Html.EditorFor(model => model.EndTime, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.EndTime, "", new { @class = "text-danger" })
            </div>
        </div>

Now I want to use DateTime instead of Date.What should be the DataFormat String?

My Try

Display(Name = "End Date Time")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}{1:HH/mm}")]
        [DataType(DataType.DateTime)]

I am getting format exception?


Solution

  • Your EditorFor() method renders an input with type="date" because of the [DataType(DataType.Date)] attribute, which will generate the browsers HTML-5 datepicker (but this is only supported in Chrome and Edge).

    To generate a HTML-5 datetimepicker, you need to render an input with type = "datetime-local" but there is no data annotation attribute for that. Instead you need to generate the type attribute yourself.

    @Html.TextBoxFor(m => m.EndTime, "{0:s}", new { @type = "datetime-local", @class = "form-control" })
    

    Note "{0:s}" is shortcut for "{0:yyyy-MM-ddTHH:mm:ss}" and will display the date and time in the browsers culture. Note also that you do not need your [DataType] attribute or the ApplyFormatInEditMode = true property in the [DisplayFormat] attribute since they apply only to EditorFor()