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

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

Thanks

1 Answer 1

6

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", ""} })
Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to add a key without a value in the object? Since the required markup is required and not required=""?
But required="" is also proper syntax. Look HTML5 required Attribute

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.