asp.net-mvc 如何将自定义数据属性和类添加到`@Html.EditorFor`?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17742488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add custom data attributes and classes to `@Html.EditorFor`?
提问by Martinffx
I want to add some custom attributes to the inputgenerated by @Html.EditorFor, I tried the following:
我想向input生成的添加一些自定义属性@Html.EditorFor,我尝试了以下操作:
@Html.EditorFor(model => model.Percent, new { @class = "percent" })
But it just ignores my class, from what I can tell from searching around is that the template doesn't support adding custom attributes.
但它只是忽略了我的类,从我四处搜索可以看出,模板不支持添加自定义属性。
But how does one create a custom template adding support for the custom attributes, while keeping all the functionality of the old template?
但是如何创建一个自定义模板添加对自定义属性的支持,同时保留旧模板的所有功能呢?
采纳答案by Brendan Vogt
Please see the following posts, this question has been asked before on Stackoverflow.
请参阅以下帖子,此问题之前已在 Stackoverflow 上问过。
- Add css class to Html.EditorFor in MVC 2
- Set the class attribute to Html.EditorFor in ASP.NET MVC Razor View
- ASP.NET MVC 3 Razor - Adding class to EditorFor
- 将 css 类添加到 MVC 2 中的 Html.EditorFor
- 在 ASP.NET MVC Razor 视图中将类属性设置为 Html.EditorFor
- ASP.NET MVC 3 Razor - 向 EditorFor 添加类
There are many more examples, just Googleit.
还有很多例子,仅Google此而已。
I hope this helps.
我希望这有帮助。
回答by Praveen M P
Using jQuery this could be done easily
使用 jQuery 这可以很容易地完成
$("input").addClass("class-name")
Input tag
输入标签
@Html.EditorFor(model=>model.Name)
For DropDownlist u can use following code
对于 DropDownlist,您可以使用以下代码
$("select").addClass("class-name")
for Dropdownlist
对于下拉列表
@Html.DropDownlistFor(model=>model.Name)
回答by wheatie
The accepted answer is incorrect.
接受的答案是不正确的。
Html.EditorFor ignores custom css class This behavior is by design.
Html.EditorFor 忽略自定义 css 类 此行为是设计使然。
回答by Bilal
Try This it works for MVC3
试试这个它适用于 MVC3
@Html.EditorFor(model => model.Percent)
<style type="text/css">
#Percent
{
width:100%;
}
</style>

