6

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; }
ar.gorgin
  • 4,765
  • 12
  • 61
  • 100
  • You need MVC 5 to use `@Html.EditorFor()` with html attributes. For MVC 4, you will need to use `@Html.TextBoxFor()` or similar. Another alternative is pass the html attributes as `AdditionalViewData` and use a custom `EditorTemplate` –  Dec 07 '14 at 08:46
  • Thanks, I want to show enum in dropdown, so i use EditorFor.I use MVC4. I can use `AdditionalViewData` for pass class to editor? – ar.gorgin Dec 07 '14 at 08:56
  • You need to include the `EditorTemplate` you use to render the dropdown –  Dec 07 '14 at 08:57
  • I have a EditorTemplate and render dropdown, but how to pass class to EditorTemplate? – ar.gorgin Dec 07 '14 at 09:00
  • If you not going to show the code, how do you expect me to help? –  Dec 07 '14 at 09:01
  • 1
    @StephenMuecke - actually, you need MVC 5.1 for html attributes, this wasn't in 5.0. – Erik Funkenbusch Dec 07 '14 at 09:27

1 Answers1

9

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)

Community
  • 1
  • 1