27

How can I generate the following input element using standard HTML helpers and Razor view engine:

<input id="Foo" name="Foo" type="text" autofocus />

Can I use the standard HTML helper or do I have to write my own?

Any help would be greatly appreciated!

3 Answers 3

46

You can pass additional HTML attributes to the TextBoxFor method:

@Html.TextBoxFor(m => m.Foo, new { autofocus="autofocus"})

Edit:
You can get only autofocus="" with:

@Html.TextBoxFor(m => m.Foo, new { autofocus=""})

All the built in helpers are using the TagBuilder class's MergeAttribute method internally, and it only supports attributes in the following format : key="value".
So if you need only autofocus you need to write your own helper with a custom html builder.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but I don't want to generate <input ... autofocus="autofocus" />
In this case you need to implement your own helper, see my updated answer.
8

Not sure what else has changed for MVC 4 regarding this scenario but I ended up using @Html.TextBoxFor(x => x.Foo, new { autofocus = true }).

Comments

7

I think autofocus="autofocus" is also valid see: http://www.w3schools.com/html5/att_input_autofocus.asp so you can use the htmlAttributes argument like so:

@Html.TextBox("Foo", null, new { autofocus = "autofocus" })

EDIT

I think you cannot use the standard HTML helpers if you really just want autofocus, you would have to do something like this:

@Html.Raw("<input id=\"Foo\" name=\"Foo\" type=\"text\" autofocus />")

2 Comments

Thanks, but I don't want to generate <input ... autofocus="autofocus" />
I edited my answer to show a method, but not using the standard TextBox, TextBoxFor stuff. Can I ask why you do not want autofocus="autofocus"?

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.