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 element that can be set according to model type, but all shapes of that can get the attributes. So is there any way to set attribute to @Html.EditorFor something like this: new {@class = "myclass"} ?
As you know we can set attributes to actionLink or textBox in razor views
Share
The
EditorForhelper 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 thehtmlAttributesargument 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:
And now when you want to render this editor template for some string property on your view model: