ASP.NET MVC HTML helper methods for new HTML5 input types

Drew Noakes picture Drew Noakes · Aug 31, 2010 · Viewed 68.6k times · Source

HTML5 appears to support a new range of input fields for things such as:

  • Numbers
  • Email addresses
  • Colors
  • URLs
  • Numeric range (via a slider)
  • Dates
  • Search boxes

Has anyone implemented HtmlHelper extension methods for ASP.NET MVC that generates these yet? It's possible to do this using an overload that accepts htmlAttributes, such as:

Html.TextBoxFor(model => model.Foo, new { type="number", min="0", max="100" })

But that's not as nice (or typesafe) as:

Html.NumericInputFor(model => model.Foo, min:0, max:100)

Answer

Paul Hiles picture Paul Hiles · May 13, 2013

Just a heads up that many of these are now incorporated into MVC4 by using the DataType attribute.

As of this work item you can use:

public class MyModel 
{
    // Becomes <input type="number" ... >
    public int ID { get; set; }

    // Becomes <input type="url" ... >
    [DataType(DataType.Url)]
    public string WebSite { get; set; }

    // Becomes <input type="email" ... >
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    // Becomes <input type="tel" ... >
    [DataType(DataType.PhoneNumber)]
    public string PhoneNumber { get; set; }

    // Becomes <input type="datetime" ... >
    [DataType(DataType.DateTime)]
    public DateTime DateTime { get; set; }

    // Becomes <input type="date" ... >
    [DataType(DataType.Date)]
    public DateTime Date { get; set; }

    // Becomes <input type="time" ... >
    [DataType(DataType.Time)]
    public DateTime Time { get; set; }
}