Geeks With Blogs

@neh123us
  • neh123us T4 sould be your outsourcing strategy https://t.co/1ZceCUKWKE T4 - The Insource Code Monkey about 510 days ago
  • neh123us Had a need for Dynamic Views in MVC today. Wanted to use a Partial view on two different views with different ViewModels about 559 days ago

News Google

Nick Harrison Blog<Nick>.Next()

I have always been surprised that this was not already baked into the framework, but it turns out it is fairly easy to add.   There are just a few steps.

 

In the end, we want a drop down that will list the valid values from the enumeration.

 

We will start by creating a new Editor Template.   The template itself is fairly straight forward:

 

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Enum>" %>

<%

             

    Func<object, string> GetDisplayName = o =>

    {

        var result = null as string;

        var display = o.GetType()

                       .GetMember(o.ToString()).First()

                       .GetCustomAttributes(false)

                       .OfType<DisplayAttribute>()

                       .LastOrDefault();

        if (display != null)

        {

            result = display.GetName();

        }

 

        return result ?? o.ToString();

    };

 

    var values = Enum.GetValues(ViewData.ModelMetadata.ModelType)

                     .Cast<Enum>()

                     .Select(v => new SelectListItem

                            {

                                Selected = v.Equals(Model),

                                Text = GetDisplayName(v)

 

                            });                               

 

%>

<%= Html.DropDownList("", values,

          new { @class = "chzn-container" })%>

 

Next we need to do a little bit of work to make sure that this template will be used.  We will create a new CustomModelMetadataProvider that will let the DataAnnotationsModelMetaDataProvider handle all of the work, but if there is not  a TableHint added and the property is an enum, we will assign our own TableHint of "Enum.

 

Because we let the base class do all of the heavy lifting, our custom model meta data provider is very simple:

 

   public class CustomModelMetadataProvider 

        : DataAnnotationsModelMetadataProvider

    {

        public override ModelMetadata GetMetadataForProperty

            (Func<object> modelAccessor, 

                    Type containerType, string propertyName)

        {

            var result = base.GetMetadataForProperty

                (modelAccessor, containerType, propertyName);

            if (result.TemplateHint == null && typeof(Enum)

                .IsAssignableFrom(result.ModelType))

            {

                result.TemplateHint = "Enum";

            }

            return result;

        }

    }

 

Finally we need to let the framework know about our new provider.   Simply add something like this to your Application_Start event handler in the global object:

 

         ModelMetadataProviders.Current = 

           new CustomModelMetadataProvider();

 

Now with a simple enum like this:

 

   public enum Occupancy

    {

        [Display(Name = "Owner Occupied")]

        OwnerOccupied, 

        [Display(Name =  "Second Home")]

        SecondHome, 

        [Display(Name = "Investment Property")]

        InvestmentProperty

    }

 

and adding to the to the View:

 

  <%=Html.EditorFor(m=>m.Occupancy) %>

 

We get a drop down that looks like this:

It may seem like a lot of work, but once this is in place, you don't have to worry about any of these steps again.

Posted on Wednesday, January 16, 2013 1:15 PM MVC | Back to top


Comments on this post: Simple way to bind an Enum to a DropDownList in MVC

# re: Simple way to bind an Enum to a DropDownList in MVC
Requesting Gravatar...
I have blogged about this last year, taking a slightly different, but comparable approach. Mayhaps nice to include some pointers or different approaches :)

Here's a link to it: http://www.jberndsen.nl/2011/12/asp-net-mvc-htmlhelper-for-enums/
Left by Jeroen on Jan 18, 2013 1:35 PM

# re: Simple way to bind an Enum to a DropDownList in MVC
Requesting Gravatar...
Hey that's great, would be awesome, if you can do an example for Enum Flags as well :)
Left by Mandeep on Jan 20, 2013 3:52 AM

# re: Simple way to bind an Enum to a DropDownList in MVC
Requesting Gravatar...
wow.Its amaze .Its helping lot and simple
Left by ramesh on Jan 20, 2013 2:17 PM

# re: Simple way to bind an Enum to a DropDownList in MVC
Requesting Gravatar...
how do you do this with html.dropdownlisfor?
Left by nick on Jan 22, 2013 12:26 PM

# re: Simple way to bind an Enum to a DropDownList in MVC
Requesting Gravatar...
This is easily adapted to flags by simply using a MultiSelectList instead of a SelectList.

I would modify the GetMetadataForProperty method to check for the custom attribute FlagsAttribute, if the attribute is there, set a different UI hint.

You could also use a collection of checkboxes, but I think that the multi item select is more expected.
Left by Nick on Jan 22, 2013 5:02 PM

# re: Simple way to bind an Enum to a DropDownList in MVC
Requesting Gravatar...
Jeroen thanks for sharing an alternate approach. That is one of the things that I like about MVC, there are many ways to do almost anything.
Left by Nick on Jan 22, 2013 5:11 PM

# re: Simple way to bind an Enum to a DropDownList in MVC
Requesting Gravatar...
Nice alternative approach! However there is this little problem called globalization...
Left by Florian Mücke on Jan 25, 2013 4:47 AM

# AMXEE INTERNATIONAL
Requesting Gravatar...
I read your post, I like it very much. It is very useful post. The most likable thing in the post is the way of the explanation , Thanks for giving me this information. Keep posting.
Left by socket screw on Jan 25, 2013 5:52 AM

# re: Simple way to bind an Enum to a DropDownList in MVC
Requesting Gravatar...
Florian Mücke,

Localization can easily be handled by pulling the display name from a resource file keyed by the Enum.DisplayName combination to get the language specific wording.
Left by Nick on Jan 25, 2013 8:34 AM

# re: Simple way to bind an Enum to a DropDownList in MVC
Requesting Gravatar...
Good blog!! You could start many more. I love all the info offered. I will stay tuned.
Left by Cooking recipes on Jan 25, 2013 1:03 PM

# re: Simple way to bind an Enum to a DropDownList in MVC
Requesting Gravatar...
nice creating but i have a small problem i need wordpress dropdown menu style creating. This function works wordpress theme function?
Left by Find best gift for your child on Jan 28, 2013 2:37 PM

# re: Simple way to bind an Enum to a DropDownList in MVC
Requesting Gravatar...
Good one !!!
Left by Varu on Jan 29, 2013 1:57 AM

comments powered by Disqus

Copyright © Nick Harrison | Powered by: GeeksWithBlogs.net | Join free