Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC3 - Html.TextBoxFor and autofocus attribute

Tags:

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!

like image 486
šljaker Avatar asked Dec 16 '11 10:12

šljaker


2 Answers

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.

like image 98
nemesv Avatar answered Oct 06 '22 00:10

nemesv


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 />") 
like image 35
kmp Avatar answered Oct 06 '22 00:10

kmp