[英]Using DataAnnotation localizer in your extension method for HtmlHelper in ASP.net core mvc 3.1
I looked to make extension method to HTML Helper to show the Description for the property of my ViewModel.我希望对 HTML Helper 进行扩展方法,以显示我的 ViewModel 属性的描述。 Here the listing, because since How do I display the DisplayAttribute.Description attribute value?这里是列表,因为我如何显示 DisplayAttribute.Description 属性值? things have changed in ASP.NET Core 3.1. ASP.NET Core 3.1 中的情况发生了变化。
Here is my extension method:这是我的扩展方法:
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;
}
But now I need localize it, like does, for instance但是现在我需要对其进行本地化,例如
@Html.DisplayNameFor(model => model.MyNotObviousProperty)
How can I retrieve DataAnnotationLocalizer in my extension method?如何在我的扩展方法中检索 DataAnnotationLocalizer? Of course, I can pass it like the argument, but it is not beautiful solution, when DisplayNameFor
not asks for additional arguments.当然,我可以像参数一样传递它,但这不是漂亮的解决方案,当DisplayNameFor
不要求额外的 arguments 时。
You just need to get a reference to IStringLocalizer
.您只需要获取对IStringLocalizer
的引用。
In your startup:在您的启动中:
public void Configure(..., IStringLocalizer stringLocalizer) // ASP.NET Core will inject it for you
{
// your current code
YourExtensionsClass.RegisterLocalizer(stringLocalizer);
}
and in your extensions class:并在您的扩展 class 中:
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];
}
}
If you want more control, I'd suggest you to get some ideas from how ASP.NET Core does internally, by taking a look at the source code (method CreateDisplayMetadata) .如果您想要更多控制,我建议您通过查看源代码(方法 CreateDisplayMetadata)从 ASP.NET Core 内部的工作方式中获得一些想法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.