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

Using DataAnnotation localizer in your extension method for HtmlHelper in ASP.net core mvc 3.1

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

I looked to make extension method to HTML Helper to show the Description for the property of my ViewModel. Here the listing, because since How do I display the DisplayAttribute.Description attribute value? things have changed in 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? Of course, I can pass it like the argument, but it is not beautiful solution, when DisplayNameFor not asks for additional arguments.

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

You just need to get a reference to 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:

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).