Johan
Johan

Reputation: 35194

Add html5 attributes to form inputs using razor

@Html.TextBox("UserName", null, new { /* ... */ })

How would i add properties like data-foo="bar" and required to the htmlattributes object?

Thanks

Upvotes: 1

Views: 2383

Answers (1)

krolik
krolik

Reputation: 5802

If you are using MVC3 you can use underscores in your html attributes, they are converted to dashes

@Html.TextBox("UserName", null, new { data_foo = "bar", required = "" })

html result

<input data-foo="bar" id="UserName" name="UserName" required="" type="text" value="">

Second option. Use dictionary instead of anonymous object

@Html.TextBox("UserName", null, new Dictionary<string, object> { {"data-foo", "bar"}, {"required", ""} })

Upvotes: 6

Related Questions