7

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; }
6
  • 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 Commented Dec 7, 2014 at 8: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? Commented Dec 7, 2014 at 8:56
  • You need to include the EditorTemplate you use to render the dropdown Commented Dec 7, 2014 at 8:57
  • I have a EditorTemplate and render dropdown, but how to pass class to EditorTemplate? Commented Dec 7, 2014 at 9:00
  • 1
    @StephenMuecke - actually, you need MVC 5.1 for html attributes, this wasn't in 5.0. Commented Dec 7, 2014 at 9:27

1 Answer 1

10

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.