Partager via


HTML5 in MVC

Live Demo - Source Code

HTML5 is a hot topic lately and developers are eagerly investigating ways to use HTML5. One of the more widely discussed capabilities are the built-in form type controls enforcing validation and allowing for placeholder values - new input types such as “color”, “date|datetime”, “email”, “phonenumber” are now supported in browsers such as Opera and Firefox.

Example:
<input name="EmailAddress" placeholder="ex
youremail@here.com" required="true" type="email" />

HTML5 is not yet standardized and not supported in the more broadly utilized browsers … so how can we leverage these capabilities when supported … and yet provide a similar experience for users of non-html5 browsers?

It was this problem that motivated me to create the example project I’ll be covering today – and I threw in a few other useful examples to scenarios often requested by customers.

First I leveraged the nuget package mvchtml5templates which provides new EditorTemplates for the HTML5 types. If you haven’t discovered nuget yet – you are in for a treat. Install the latest version from nuget.org – and you can set Package Manager to check for updates automatically via VS2010 Tools|Options|Package Manager| Automatically "Check for Updates" checkbox.

The EditorTemplates will output <input> with the native html5 types, then I used Modernizer in Javascript to check if the type is supported by the browser.

Example:

if (!Modernizr.inputtypes.email))…

Modernizer uses a combination of pre-defined browser capabilities and real-time client-side capability checks to determine this. If it is supported – then we get the benefit validation and native browser controls for the types. If not – then we leverage JQuery for validation, generating controls for the given type (eg date and color) and placeholder.

There are also a few of other scenarios I’ve covered in this example that I’ll describe in future blog posts such as:

  • Using a JQuery Dialog for the item editing with Ajax and the AntiForgeryToken.
  • Deleting a row from the grid using Ajax and without a full grid refresh.
  • Leveraging ViewModels.
  • Supporting IoC / Repository pattern.
  • Dev vs. Production setup for Jquery references
  • T4MVC