unable to apply Bootstrap classes to my EditorFor

不问归期 提交于 2019-11-28 14:03:06

Yes, to pass html attributes to a standard EditorFor() you need MVC-5.1+. If you want to replicate this with MVC-5, you can create a custom editor template and pass the attributes using the overload that accepts additionViewData. For example, create a new EditorTemplate named "String.cshtml" to apply the template for all properties that are typeof string

/Views/Shared/EditorTemplates/String.cshtml

@Html.TextBoxFor(m => m, ViewData["attributes"])

and in the view

@Html.EditorFor(m => m.Name, new { attributes = new { @class = "form-control" } })

or create a specificEditorTemplate

/Views/Shared/EditorTemplates/MyCustomTemplate.cshtml

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, ViewData["htmlAttributes"])

and in the view

@Html.EditorFor(m => m.Name, "MyCustomTemplate", new { attributes = new { @class = "form-control" } })

The second example shows how to respect the DisplayFormat attribute as mentioned in your comments above, for example

[DisplayFormat(DataFormatString="{0:C}", ApplyFormatInEditMode = true)]
public decimal Amount { get; set; }

will format the value as a currency string.

This answer also gives some other options including creating a custom html helper for rendering bootstrap controls

This works:

@Html.EditorFor(x => x.Created, new { htmlAttributes = new { @class = "date" } })
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!