1

I've got an ASP.NET MVC 5 application. Date fields are prolific. Things are working and behaving propertly, however the W3C Markup Validator complains about the date text fields having an improper type attribute value.

I'm rendering the input's for DateTime or nullable DateTime properties using the EditorFor helper:

@Html.EditorFor(model => model.BeginDate)

This is getting translated to:

<input type="datetime">

The "datetime" value of the type attribute is no longer a standard according to the W3C HTML5 Forms standard. The supported date/time types are:

  • date - A date (year, month, day) with no time zone
  • time - A time (hour, minute, seconds, fractional seconds) with no time zone

I don't really want to create a custom Editor Template, because the standard MVC editor template works perfectly, except the type="datetime" attribute value is non-standard.

How can I override the default behavior of the EditorFor method for DateTime objects so it creates <input type="date"> elements without creating my own Editor Template?

Greg Burghardt
  • 17,900
  • 9
  • 49
  • 92

1 Answers1

3

Annotate your model field with the DataType attribute

public class Model1
{
    [DataType(DataType.Date)]
    public DateTime BegineDate { get; set; }
}
Fran
  • 6,440
  • 1
  • 23
  • 35
  • Which namespace is the `DataType` enum in? I'm not able to resolve that symbol to a namespace in my current project. I'm wondering if I'm missing an assembly reference. – Greg Burghardt Jan 11 '17 at 16:52
  • using System.ComponentModel.DataAnnotations; – Fran Jan 11 '17 at 16:53
  • Never mind. I figured it out. I'm using NHibernate, which has a class NHibernate.Type.DataType, and then there is System.ComponentModel.DataAnnotations.DataType. My problem is clash of namespaces. Visual studio just got weird on my briefly. – Greg Burghardt Jan 11 '17 at 16:55
  • Works perfectly! Now to just get Microsoft to change the default behavior of the MVC framework... – Greg Burghardt Jan 11 '17 at 16:55