我希望对HTML Helper进行扩展,以显示ViewModel属性的Description。在这里列出,因为自从我如何显示DisplayAttribute.Description属性值?在ASP.NET Core 3.1中,情况发生了变化。
这是我的扩展方法:
public static string DescriptionFor<TModel, TValue>(this IHtmlHelper<TModel> self, Expression<Func<TModel, TValue>> expression) {
MemberExpression memberExpression = (MemberExpression)expression.Body;
var displayAttribute = (DisplayAttribute)memberExpression.Member.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault();
string description = displayAttribute?.Description ?? memberExpression.Member?.Name;
//But how can i localize this description
return description;
}
但是现在我需要将其本地化,例如
@Html.DisplayNameFor(model => model.MyNotObviousProperty)
如何在扩展方法中检索DataAnnotationLocalizer?当然,我可以像参数一样传递它,但是当DisplayNameFor
不要求其他参数时,这不是一个很好的解决方案。
你只需要参考即可IStringLocalizer
。
在你的启动中:
public void Configure(..., IStringLocalizer stringLocalizer) // ASP.NET Core will inject it for you
{
// your current code
YourExtensionsClass.RegisterLocalizer(stringLocalizer);
}
在你的扩展程序类中:
public static class YourExtensionsClass
{
private static IStringLocalizer _localizer;
public static void RegisterLocalizer(IStringLocalizer localizer)
{
_localizer = localizer;
}
public static string DescriptionFor<TModel, TValue>(this IHtmlHelper<TModel> self, Expression<Func<TModel, TValue>> expression)
{
MemberExpression memberExpression = (MemberExpression)expression.Body;
var displayAttribute = (DisplayAttribute)memberExpression.Member.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault();
string description = displayAttribute?.Description ?? memberExpression.Member?.Name;
return _localizer[description];
}
}
如果需要更多控制,建议你通过查看源代码(方法CreateDisplayMetadata)来了解ASP.NET Core在内部的工作方式。
谢谢!我有自己的IStringLocalizerFactory可以将类型转换为合适的资源位置,因为资源文件位置的默认约定对我的项目不是很舒服。所以我更改了方法:description = _LocalizerFactory.Create(memberExpression.Expression.Type)[description];