Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Localized enum strings in SelectList

In my MVC3 app. I'm using select list to populate combo box with enum values like this

<div class="editor-field">
   @Html.DropDownListFor(x => x.AdType, new SelectList(Enum.GetValues(typeof(MyDomain.Property.AdTypeEnum))), " ", new { @class = "dxeButtonEdit_Glass" })
</div>

MyDomain.Property looks like this

 public enum AdTypeEnum 
 {
     Sale = 1,           
     Rent = 2,           
     SaleOrRent = 3 
 };

How can I use my localized strings to localize these enums?

like image 463
BobRock Avatar asked Dec 13 '22 04:12

BobRock


1 Answers

You could write a custom attribute:

public class LocalizedNameAttribute: Attribute
{
    private readonly Type _resourceType;
    private readonly string _resourceKey;

    public LocalizedNameAttribute(string resourceKey, Type resourceType)
    {
        _resourceType = resourceType;
        _resourceKey = resourceKey;
        DisplayName = (string)_resourceType
            .GetProperty(_resourceKey, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)
            .GetValue(null, null);
    }

    public string DisplayName { get; private set; }
}

and a custom DropDownListForEnum helper:

public static class DropDownListExtensions
{
    public static IHtmlString DropDownListForEnum<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression,
        string optionLabel,
        object htmlAttributes
    )
    {
        if (!typeof(TProperty).IsEnum)
        {
            throw new Exception("This helper can be used only with enum types");
        }

        var enumType = typeof(TProperty);
        var fields = enumType.GetFields(
            BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public
        );
        var values = Enum.GetValues(enumType).OfType<TProperty>();
        var items =
            from value in values
            from field in fields
            let descriptionAttribute = field
                .GetCustomAttributes(
                    typeof(LocalizedNameAttribute), true
                )
                .OfType<LocalizedNameAttribute>()
                .FirstOrDefault()
            let displayName = (descriptionAttribute != null)
                ? descriptionAttribute.DisplayName
                : value.ToString()
            where value.ToString() == field.Name
            select new { Id = value, Name = displayName };

        var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        var enumObj = metadata;
        var selectList = new SelectList(items, "Id", "Name", metadata.Model);
        return htmlHelper.DropDownListFor(expression, selectList, optionLabel, htmlAttributes);
    }
}

And then it's easy:

Model:

public enum AdTypeEnum
{
    [LocalizedName("Sale", typeof(Messages))]
    Sale = 1,
    [LocalizedName("Rent", typeof(Messages))]
    Rent = 2,
    [LocalizedName("SaleOrRent", typeof(Messages))]
    SaleOrRent = 3
}

public class MyViewModel
{
    public AdTypeEnum AdType { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel
        {
            AdType = AdTypeEnum.SaleOrRent
        });
    }
}

View:

@model MyViewModel

@Html.DropDownListForEnum(
    x => x.AdType, 
    " ",
    new { @class = "foo" }
)

Finally you should create a Messages.resx file which will contain the necessary keys (Sale, Rent and SaleOrRent). And if you want to localize you simply define a Messages.xx-XX.resx with the same keys for a different culture and swap the current thread culture.

like image 188
Darin Dimitrov Avatar answered Jan 16 '23 01:01

Darin Dimitrov