How to add custom data attributes and classes to `@Html.EditorFor`?

佐手、 提交于 2019-12-31 00:45:16

问题


I want to add some custom attributes to the input generated by @Html.EditorFor, I tried the following:

@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?


回答1:


Please see the following posts, this question has been asked before on 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

There are many more examples, just Google it.

I hope this helps.




回答2:


Using jQuery this could be done easily

$("input").addClass("class-name")

Input tag

@Html.EditorFor(model=>model.Name)

For DropDownlist u can use following code

$("select").addClass("class-name")

for Dropdownlist

@Html.DropDownlistFor(model=>model.Name)



回答3:


The accepted answer is incorrect.

Html.EditorFor ignores custom css class This behavior is by design.

http://aspnetwebstack.codeplex.com/workitem/223




回答4:


Try This it works for MVC3

@Html.EditorFor(model => model.Percent)

<style type="text/css">

#Percent
{

   width:100%;

}

</style>


来源:https://stackoverflow.com/questions/17742488/how-to-add-custom-data-attributes-and-classes-to-html-editorfor

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