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"}
?
问题:
回答1:
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" })
回答2:
Try this:
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
回答3:
Add custom attributes as
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @data_minlength = "3", @class = "form-control input-md", @placeholder = "Name", @required = "required", @id= "txtName"} })
Replace data- to @data_
It will generate correct html with data-
回答4:
I believe that the original poster was correct
each
EditorFor()
creates a main
HTML element
(though there may be others present), so it would be very helpful to be able to pass an object containingHTML attributes
to apply to that mainHTML element
.I want to apply the
HTML 5
'autofocus' attribute to one field on every form,but I DO NOT want to have to write custom code.
I hate the fact that I'm currently reduced to using, e.g.,
@Html.TextBoxFor()
for that one field just so that I can apply specific attributes to theinput element
.The
EditorFor()
method does have a parameter they calladditionalViewData
, but I have no idea what you can do with that and searching on MSDN has not been of any help to me.
回答5:
Try this simple code for adding class to @Html.EditorFor()
@Html.EditorFor(x => x.Demo)
<style type="text/css">
#Demo
{
color:#fff;
width: 50%;
}
</style>
this code works fine for MVC3