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

70,767

Solution 1

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; }
}

Solution 2

Check out the ASP.net MVC HTML5 Helpers Toolkit

Solution 3

Easiest way is to simply add type="Email" as an html attribute. It overrides the default type="text". Here is an example with a html5 required validator also:

@Html.TextBox("txtEmail", "", 
    new { placeholder = "email address", 
          @type="email", 
          @required = ""
    })

Solution 4

What i don't like about DataTypes Attributes is that u have to use EditorFor in the view. Then, you can't use htmlAttributes to decorate your tag. There are other solutions but i prefer this way.

In this example i only extended the signature i use the most.

So in the class:

using System.Linq.Expressions;
namespace System.Web.Mvc.Html
{
    public static class HtmlExtensions
    {
        public static MvcHtmlString EmailFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, Object htmlAttributes)
        {
            MvcHtmlString emailfor = html.TextBoxFor(expression, htmlAttributes);
            return new MvcHtmlString(emailfor.ToHtmlString().Replace("type=\"text\"", "type=\"email\""));
        }
    }
}

As you see i just changed the type="text" for type="email" and then i can use in my view:

    <div class="form-group">            
        @Html.LabelFor(m => m.Email, new { @class = "col-lg-2 control-label" })
        <div class="col-lg-10">
            @Html.EmailFor(m => m.Email, new { @class = "form-control", placeholder = "Email" })
            @Html.ValidationMessageFor(m => m.Email)                                 
        </div>            
    </div>

And the html source gives:

<div class="form-group">            
    <label class="col-lg-2 control-label" for="Email">Email</label>
    <div class="col-lg-10">
        <input class="form-control" data-val="true" data-val-required="The Email field is required." id="Email" name="Email" placeholder="Email" type="email" value="" />
        <span class="field-validation-valid" data-valmsg-for="Email" data-valmsg-replace="true"></span>                                 
    </div>            
</div> 

Solution 5

Love it when can drive this type of stuff off the model!! I decorated my models with [DataType(DataType.PhoneNumber)], and all but one worked.

I realized the hard way that @Html.TextBoxFor doesn't render the type="<HTML5 type>" but @Html.EditorFor does. Makes sense I guess now that I think about it, but posting this to maybe save others the frustrating few minutes that I just lost;)

Share:
70,767
Drew Noakes
Author by

Drew Noakes

Developer on .NET at Microsoft.

Updated on July 09, 2022

Comments

  • Drew Noakes
    Drew Noakes almost 2 years

    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)
    
  • Paul Hiles
    Paul Hiles about 11 years
    @Drew - believe date, datetime and time are included in that work item (they are certainly part of mvc4 release). why do you say otherwise?
  • Drew Noakes
    Drew Noakes about 11 years
    I misinterpreted the comment: We need to do this automatically for tel, url, email, datetime, date, time, and number. I've linked to the docs and extended the sample code. Nice find, thanks.
  • Erik Funkenbusch
    Erik Funkenbusch almost 11 years
    FYI, you can in fact use html attributes with EditorFor, but you would have to write your own template for it. Which is a lot less intrusive than writing a new Html helper.
  • RPAlbert
    RPAlbert almost 11 years
    I agree with u and i did see a few remarks about using templates. Sadly i'm only at the learning stage in MVC right now and didn't take the time to look at Editor and Display templates.
  • QMaster
    QMaster over 10 years
    In my case not working with TextBoxFor and EditorFor in both of IE and Chrome, What is the wrong you think?
  • Yecats
    Yecats about 10 years
    As of MVC 5.1 you can use HTML attributes with EditorFor tags.
  • Drew Noakes
    Drew Noakes about 10 years
    That's pretty much what I show in the original question. I was looking for a more typesafe solution.
  • dalcam
    dalcam about 10 years
    Hi @Drew - your are completely right, by the time i read the answers I had forgotten your original question - sorry!
  • Drew Noakes
    Drew Noakes about 10 years
    No worries. Your code definitely works, but I would like to avoid using anonymous types, both for performance and because they're not checked by the compiler for correctness.
  • Revious
    Revious over 9 years
    doesn't MVC support HTML5 by deafault?
  • Alex from Jitbit
    Alex from Jitbit over 9 years
    This answer definitely worth being here. Googled this question up - found this solution
  • Nick
    Nick over 8 years
    This is the answer I found most easy to implement. I didn't want to have to use Editor helper, and this answer supports that inclination.