ASP.NET MVC: Creating localized DropDownLists for enums


A collection of HTML helpers that generate DropDownlists for enums, with or without localization support.

Table of contents

 

HTML Helpers Overview

I’ve created a set of HTML helpers that generate a DropDownList for an enum.
Those helpers are similar to DropDownList Method and DropDownListFor Method, with the only difference being that the those helpers will populate the DropDownList with the elements of the specified enum.

 

Some examples – Basic usage

Let’s assume the following model:

public enum WeekDay
{
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
}

public class WeeklyEvent
{
    public string Title { get; set; }
    public WeekDay Day { get; set; }
    public WeekDay? AnotherDay { get; set; }
}

 

Setting the name of the element and default empty item text

This is the most basic usage, the generated text will be enumValue.ToString():

// name="eventDay"
@Html.EnumDropDownList<WeekDay>("eventDay", "Select an item")

// name="Day"
@Html.EnumDropDownListFor<WeeklyEvent, WeekDay>(x => x.Day, "Select an item")

Html.EnumDropDownListFor works with nullables too:

@Html.EnumDropDownListFor<WeeklyEvent, WeekDay?>(x => x.AnotherDay, "Select an item")

 

Using [Description] attribute

You can customize the text using DescriptionAttribute:

public enum WeekDay
{
    [Description("Domingo")]
    Sunday,

    [Description("Segunda")]
    Monday,

    [Description("Terça")]
    Tuesday,

    [Description("Quarta")]
    Wednesday,

    [Description("Quinta")]
    Thursday,

    [Description("Sexta")]
    Friday,

    [Description("Sábado")]
    Saturday
}

 

Using custom HTML attributes

Just like DropDownList and DropDownListFor, you can use custom HTML attributes

@Html.EnumDropDownList<WeekDay>("eventDay", "Select an item", new { @class="select"})

@Html.EnumDropDownListFor<WeeklyEvent, WeekDay>(x => x.Day, "Select an item" , new { @class="select"})

More examples – Localization support

The resource file keys for the enum values have the following naming convention: {EnumName}.{EnumValue}
Considering the following resource – type MyResources:

Using [LocalizationEnum] attribute

Just set the [LocalizationEnum] attribute to the enum, specifying the type of the resource object:

[LocalizationEnum(typeof(MyResources))]
public enum WeekDay
{
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
}

The usage is the same as the previous examples:

@Html.EnumDropDownList<WeekDay>("selectDay", "")

 

Specifying the resource object type

If you can’t or don’t want to use the [LocalizationEnum] attribute, you can specify the resource type using the following helpers:

@Html.EnumDropDownList<WeekDay, MyResources>("selectDay", "")

@Html.EnumDropDownListFor<WeeklyEvent, WeekDay, MyResources>(x => x.Day, "", new {id = "myEventDay"})

 

References

ASP.NET MVC – Creating a DropDownList helper for enums

[MSDN] SelectExtensions Class

 

Downloads

Download the demo project: MvcLocalizationEnumHelpers.zip

About these ads

12 thoughts on “ASP.NET MVC: Creating localized DropDownLists for enums

  1. Hi, is it possible to store in the database only an ID of the Enum instead of storing the all description and then map it to do the complete single record display (for example an enum colors, and display a car’s color)? Thanks.

      • Thanks for this, this is what I’ve been looking for.

        I’m interested in just storing an id in the database like Patrick and I have no need for localization so I’m not too worried about that piece. Unfortunately I’m stuck trying to get the EnumDropDownListFor to set the correct value for my model. It saves to the database correctly, but I can’t seem to get an expression that correctly sets the int value…

        This throws an error.

        public enum WeekDay
        {
        Sunday = 1,
        Monday = 2,
        Tuesday = 3,
        Wednesday = 4,
        Thursday = 5,
        Friday = 6,
        Saturday = 7
        }

        @(Html.EnumDropDownListFor(x=> (int?)x.Day, “Select an item”))

        Any thoughts? Sorry for the noob question. It’s been a while since I did much .net mvc

      • Hi Kayluhb,

        I had a typo in the article, now it’s fixed.
        If your property is nullable you should use the helper like this:

        @Html.EnumDropDownListFor(x => x.Day, “Select an item”)

        Replace “WeeklyEvent” with the type of your model

      • Thanks.

        Hmm, that doesn’t seem to work either. It appears that the issue is that @model.Day returns “Sunday” where I need it to be 1 and I’m not sure how to cast the return of the lambda as an int?

  2. Do I need to do anything special to have this work for a value inside a list of objects in my model?

    <%= Html.EnumDropDownListFor(m => .CategoryActions[i].ActionName,””) %>

    It doesn’t seem to be recognizing my lambda function as the handling the proper types.

    • Hi Jeff,

      Sorry for the late reply, I haven’t got much time to take a look into this particular issue.
      Try to set the “name” property manually, something like:

      Html.EnumDropDownListFor(m => .CategoryActions[i].ActionName,””, new { name=string.Format(“CategoryActions[{0}].ActionName”, i.ToString()) })

      It’s not the most elegant solution, but it should work for now.

      Hope it helps,
      Rui

  3. Pingback: ASP.NET MVC: Creating localized DropDownLists... | Microsoft | Syngu

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s