Warm tip: This article is reproduced from serverfault.com, please click

c#-在ASP.net Core MVC 3.1中的HtmlHelper扩展方法中使用DataAnnotation本地化器

(c# - Using DataAnnotation localizer in your extension method for HtmlHelper in ASP.net core mvc 3.1)

发布于 2020-08-08 09:35:39

我希望对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不要求其他参数时,这不是一个很好的解决方案

Questioner
dmi
Viewed
0
Camilo Terevinto 2020-08-08 17:56:05

你只需要参考即可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在内部的工作方式