Reputation: 2643
I can do this easily using a TextBoxFor
but how do I do it with an EditorFor
?
I figured using the DataAnnotation [DataType(DataType.EmailAddress)]
but that doesn't do it.
I don't quite understand what the DataType
annotation actually does because it doesn't seem to do anything at all at first glance.
Upvotes: 16
Views: 27698
Reputation: 18361
The EditorFor
helper method is somewhat limited out of the box and doesn't yet appear to support the HTML5 type="email"
attribute.
Your options right now seem to be either using TextBoxFor
or creating a custom template that will allow you to set the input's type
attribute. Here's another thread that reviews some of the options for creating your own templates.
The DataAnnotation [DataType(DataType.EmailAddress)]
is actually quite useful. It sets the id
and name
of your form field to email
, which you can use with jQuery validation to show the user client-side validation messages. Applying the DataAnnotation
to your model class also means that the email property on your model will be automatically validated on the server side. If you enable unobtrusive validation in your app, you get client- and servers-side validation almost for free.
Upvotes: 8
Reputation: 1751
As an addition to jortizromo's answer, you have now at least two options:
Specifying @type
in the htmlAttributes
parameter for method EditorFor()
as in
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @type = "email" } })
Using the EmailAddress
annotation attribute from System.ComponentModel.DataAnnotations
namespace in the model class definition for the corresponding Email
property and a simple call to method EditorFor() (this provides HTML validation data tags which could be a good or bad idea depending on your task) as in
ViewModel
[EmailAddress]
public string Email { get; set; }
Razor View
@Html.EditorFor(model => model.Email)
Upvotes: 9
Reputation: 824
it seems to be supported now.
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control", @type = "email" } })
Upvotes: 16
Reputation: 629
You can override the HTML Attributes, to which a browser will fallback to type='text'
if they do not support it:
@Html.TextBoxFor(m => m.Email, new { @type = "email" })
Upvotes: 18