Asp.net mvc 3 SelectList中的本地化枚举字符串
在我的MVC3应用程序中。我使用select list用如下枚举值填充组合框Asp.net mvc 3 SelectList中的本地化枚举字符串,asp.net-mvc-3,model,enums,Asp.net Mvc 3,Model,Enums,在我的MVC3应用程序中。我使用select list用如下枚举值填充组合框 <div class="editor-field"> @Html.DropDownListFor(x => x.AdType, new SelectList(Enum.GetValues(typeof(MyDomain.Property.AdTypeEnum))), " ", new { @class = "dxeButtonEdit_Glass" }) </div> publi
<div class="editor-field">
@Html.DropDownListFor(x => x.AdType, new SelectList(Enum.GetValues(typeof(MyDomain.Property.AdTypeEnum))), " ", new { @class = "dxeButtonEdit_Glass" })
</div>
public enum AdTypeEnum
{
Sale = 1,
Rent = 2,
SaleOrRent = 3
};
如何使用本地化字符串本地化这些枚举 您可以编写自定义属性:
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; }
}
和一个自定义的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);
}
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
AdType = AdTypeEnum.SaleOrRent
});
}
}
视图:
最后,您应该创建一个Messages.resx
文件,该文件将包含必要的密钥(Sale
、Rent
和salerent
)。如果您想本地化,只需使用不同区域性的相同键定义一个Messages.xx xx.resx
,并交换当前线程区域性
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
AdType = AdTypeEnum.SaleOrRent
});
}
}
@model MyViewModel
@Html.DropDownListForEnum(
x => x.AdType,
" ",
new { @class = "foo" }
)