Asp.Net Mvc - Html.TextBox - Set Autofocus property

痴心易碎 提交于 2020-01-02 01:08:48

问题


In Html 5, there is a new attribute on textbox called autofocus.

The problem is that it is a boolean value (there or not there)

It should look something like :

<input name="a" value="" autofocus>

I tried :

<%= Html.TextBox( "a", null, new { autofocus } ) %>

But, it gives me an error because I'm not setting a value to autofocus...

I know I can do it manually, but can I do it with Html.TextBox ?


回答1:


Try <%= Html.TextBox( "a", null, new { autofocus = "" } ) %>

According to the HTML5 spec on boolean attributes:

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

So either

  • <input name="a" value="" autofocus> or
  • <input name="a" value="" autofocus=""> or
  • <input name="a" value="" autofocus="autofocus">

should be valid.




回答2:


Also, you can do following along with some other attributes:

@Html.TextBoxFor(m => m.Email, new { @class = "class1", @placeholder = "Email", @autofocus = "autofocus" })

Note: Only issue with autofocus is that, in IE browsers, placeholder text does not get displayed when the input control is in focus (it's an issue with IE).




回答3:


As of XHTML, the standard way to enable such a boolean attribute would be:

<input name="a" value="" autofocus="autofocus" />

therefore, assuming that is still valid in HTML5, you could use the following code:

<%=Html.TextBox( "a", null, new { autofocus: "autofocus" } ) %>


来源:https://stackoverflow.com/questions/2998247/asp-net-mvc-html-textbox-set-autofocus-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!