Back to all posts

Date Fields, ASP.NET MVC, HTML5, and Web Browsers

Posted on Sep 07, 2016

Posted in category:
Development
ASP.NET

Life as a developer with our current tools is quite amazing.  Even those of us without any real "creative" side can build applications that look nice, that accept user inputs nicely and provide a decent user experience.  The one downside to these features is the different times where we can be tricked by the tools and trying to track an issue down will result in needing to dig deep to find the "right" solution for the situation at hand.  In this case, I'll share a quick tip with dates & MVC and HTML5.

The Problem

The goal was simple, create a view model with two date inputs; "Start Date" and "End Date" to serve as a form to change a report.  By default, the form should start with January 1st of the current year for the start date, and the current date for the end.  The setup is quite simple and our view model definition would be similar to that of others.  Possibly with a property defined similar to the following.

Non-Working Code
[Display(Name = "Start Date")]
[DataType(DataType.Date)]
public DateTime StartDate{ get; set; }

On the view side of things, we used a simple @Html.EditorFor() designation. We noticed in some browsers that we got what we desired. The form would load with any of our pre-filled values, however, on more modern browsers we wouldn't get the proper display. Most notably Google Chrome would show a field without any default value. There were no errors recorded to the console, or anything telling us what we need to do.

The Fix

Funnily enough, the fix is actually to just modify the date format needed for input with a type of "date". This can be done using a declaration to go alongside our DataType definition. Simply changing our View Model definition to the below resulted in 100% success in testing thus far.

Working Code
[Display(Name = "Start Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime StartDate{ get; set; }

Conclusion

A simple solution for a very annoying problem. I hope this helps! I am trying to get through a backlog of pending blog posts so remember to share your ideas for new content as well!.