2010-06-08 32 views
13

在Html 5中,文本框上有一個名爲自動對焦的新屬性。Asp.Net Mvc - Html.TextBox - 設置自動對焦屬性

的問題是,它是一個布爾值(有或沒有出現)

它應該是這個樣子:

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

我想:

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

但是,它給我錯誤,因爲我沒有設置自動對焦值...

我知道我可以做到manuall y,但是我可以用Html.TextBox來做到嗎?

回答

23

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

按照HTML5 spec on boolean attributes

如果該屬性出現,其值必須是在空字符串或一個值,該值是針對一個ASCII不區分大小寫匹配屬性的規範名稱,沒有前導或尾隨空格。

因此,無論

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

應該是有效的。

3

隨着XHTML的,標準的方式來實現這樣一個布爾屬性是:

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

,假設仍是有效的HTML5,你可以使用下面的代碼:

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

另外,還可以做其他一些屬性下面一起:

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

注:唯一的問題機智h自動對焦是,在IE瀏覽器中,當輸入控件處於焦點狀態時(這是IE的問題),佔位符文本不會顯示。