Set the class attribute to Html.EditorFor in ASP.NET MVC Razor View

后端 未结 5 902
时光说笑
时光说笑 2020-12-30 20:03

As you know we can set attributes to actionLink or textBox in razor views but how can we set attributes to @Html.EditorFor, I know the EditorFor is a dynamic el

5条回答
  •  时光取名叫无心
    2020-12-30 20:53

    The EditorFor helper renders the corresponding editor template. It could be the default template or some custom template that you wrote. This template could contain any markup. It could contain many DOM elements. So now you understand that asking for applying a class to a template doesn't make any sense. To which element on this template you want this class to be applied? For example with the TextBoxFor helper you know that it will generate a single input field, so it makes sense to talk about applying a CSS class to it (that's exactly what the htmlAttributes argument allows you to do).

    This being said there are different techniques. For example one that I like very much is to write a custom data annotations model metadata provider and custom editor templates as outlined in the following blog post.

    Another possibility is to customize the default templates (as shown in the Brad Wilson's blog post) and apply different HTML attributes to the corresponding input field. Let's take an example with the string.cshtml editor template:

    @model string
    @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, ViewData)
    

    And now when you want to render this editor template for some string property on your view model:

    @Html.EditorFor(x => x.SomeStringProperty, new { @class = "myclass" })
    

提交回复
热议问题