d456
d456

Reputation: 1167

Is it possible to set type of input generated by TextBoxFor

I am using ASP.NET MVC 3 TextBoxFor in a form and would like to use type="email" for easier input for at least some mobile devices but cannot find how to set it using TextBoxFor. Is this not easily possible?

In View

@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email)

In model

[StringLength(50)]
public string Email { get; set; }

(Already using a data annotation to protect size constraint in DB)

Upvotes: 28

Views: 27089

Answers (4)

arnoldrob
arnoldrob

Reputation: 833

[StringLength(50)]
[DataType(DataType.EmailAddress, ErrorMessage = "Invalid Email Address")]
public string EmailAddress { get; set; }

Try to add this. I think it works.

Upvotes: 1

Toan
Toan

Reputation: 361

You're using it the wrong way.

Use EditorFor in View:

@Html.LabelFor(m => m.Email)
@Html.EditorFor(m => m.Email)

In model, add the [DataType( DataType.EmailAddress )] Data Annotations property:

[DataType( DataType.EmailAddress )]
public string Email { get; set; }

Upvotes: 3

Xordal
Xordal

Reputation: 1369

Try to use

@Html.TextBoxFor(m => m.Email, new { @type = "email" })

http://msdn.microsoft.com/en-us/library/ee703538.aspx (htmlAttributes)

Upvotes: 59

Forty-Two
Forty-Two

Reputation: 7605

Try adding [DataType( DataType.EmailAddress )] to the email property.

[DataType( DataType.EmailAddress )]
[StringLength(50)]
public string Email { get; set; }

Upvotes: 2

Related Questions