在我的MVC3应用中。我正在使用选择列表用这样的枚举值填充组合框
<div class="editor-field">
@Html.DropDownListFor(x => x.AdType, new SelectList(Enum.GetValues(typeof(MyDomain.Property.AdTypeEnum))), " ", new { @class = "dxeButtonEdit_Glass" })
</div>
MyDomain.Property看起来像这样
public enum AdTypeEnum
{
Sale = 1,
Rent = 2,
SaleOrRent = 3
};
如何使用我的本地化字符串来本地化这些枚举?
答案 0 :(得分:13)
您可以编写自定义属性:
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
帮助:
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 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; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
AdType = AdTypeEnum.SaleOrRent
});
}
}
查看:
@model MyViewModel
@Html.DropDownListForEnum(
x => x.AdType,
" ",
new { @class = "foo" }
)
最后,您应该创建一个Messages.resx
文件,其中包含必要的密钥(Sale
,Rent
和SaleOrRent
)。如果你想本地化你只需用不同文化的相同键定义Messages.xx-XX.resx
并交换当前的线程文化。