September 07, 2016

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

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.

[Display(Name = "Start 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 a 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.

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


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!.

tags: Quick Tips, ASP.NET MVC
comments powered by Disqus

Content provided in this blog is provided "AS-IS" and the information should be used at your own discretion.  The thoughts and opinions expressed are the personal thoughts of Mitchel Sellers and do not reflect the opinions of his employer.

Content Copyright

Content in this blog is copyright protected.  Re-publishing on other websites is allowed as long as proper credit and backlink to the article is provided.  Any other re-publishing or distribution of this content is prohibited without written permission from Mitchel Sellers.