Localized enum strings in SelectList

In my MVC3 application. I am using a select list to populate a combo box with enum values ​​like

<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 localized strings to localize these enums?

+3


source to share


1 answer


You can write your own 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 must create a file Messages.resx

that contains the required keys ( Sale

, Rent

and SaleOrRent

). And if you want to localize, you just define Messages.xx-XX.resx

with the same keys for a different culture and swap the current flow culture.

+12


source







All Articles