2012-08-11 100 views
0
@Html.TextBox("UserName", null, new { /* ... */ }) 

我怎么会添加像data-foo="bar"required到htmlattributes对象的属性来形成输入?添加HTML5属性使用剃刀

感谢

回答

5

如果您正在使用MVC3,你可以在你的HTML属性使用下划线,它们被转换为破折号

@Html.TextBox("UserName", null, new { data_foo = "bar", required = "" }) 

HTML结果

<input data-foo="bar" id="UserName" name="UserName" required="" type="text" value=""> 

第二个选项。使用字典而不是匿名对象

@Html.TextBox("UserName", null, new Dictionary<string, object> { {"data-foo", "bar"}, {"required", ""} }) 
+0

谢谢,正是我所需要的 – Johan 2012-08-11 13:00:40

+0

是否有可能添加一个没有对象值的键?由于'required'标记是'required'而不是'required =“”'? – Johan 2012-08-11 13:03:36

+0

但'required =“”'也是合适的语法。看[HTML5必填属性](http://www.w3schools.com/html5/att_input_required.asp) – krolik 2012-08-11 13:47:53