Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

css - Adding class to EditorFor in MVC

I want to show Enum in EditorFor. I use Editor Template for show it.(DropDownList).

I have malty EditorFor in view. I want to set class for some controls.

@Html.EditorFor(m => m.Position, new { @class = "smallinput", style = "width:150px !important" })
@Html.EditorFor(m => m.DocumentType)

In Editor: Views/Shared/DisplayTemplates/Enum.cshtml

@model Enum
@{
   var values = Enum.GetValues(ViewData.ModelMetadata.ModelType).Cast<object>()
                 .Select(v => new SelectListItem
                 {
                     Selected = v.Equals(Model),
                     Text = v.GetDisplayName(),
                     Value = v.ToString()
                 });
}
@Html.DropDownList("", values)

In Model

[DisplayName("??? ???")]
[UIHint("Enum")]
public DocumentType DocumentType { get; set; }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can pass the class name to the EditorTemplate using AdditionalViewData.

In the main view

@Html.EditorFor(m => m.DocumentType, new { htmlAttributes = new { @class = "myclass" } })

and in the EditorTemplate

....
@Html.DropDownListFor(m => m, values, ViewData["htmlAttributes"])

However including the logic for the SelectList in an EditorTemplate is not good practice. I would recommend your consider creating an extension method for generating the SelectList and then this EditorTemplate wont be required. Refer this example. And Selected = v.Equals(Model), is pointless because the Selected property will be ignored (the selected item will be the value of DocumentType)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...