How to translate a message using XLocalizer in a static method

27 views Asked by At

I have created an extension method to show an error message to the user.

I have this at this time:

    public static IHtmlContent InvalidTooltipFor<TModel, TResult>(this IHtmlHelper<TModel> htmlhelper, Expression<Func<TModel, TResult>> expression)
    {
        var builder = new HtmlContentBuilder();

        MemberExpression memberExpression = (MemberExpression)expression.Body;

        PropertyInfo? property = typeof(TModel).GetProperty(memberExpression.Member.Name);

        RequiredAttribute? attribute = (RequiredAttribute?)property?
            .GetCustomAttributes(typeof(RequiredAttribute), true)
            .FirstOrDefault();
        if (attribute != null)
            builder.AppendHtml($"<div class=\"invalid-tooltip\">{attribute.FormatErrorMessage(memberExpression.Member.Name)}</div>");

        return builder;
    }

attribute.FormatErrorMessage(memberExpression.Member.Name) call returns a message in English. How can I use the XLocalizer service to translate it? Default message for required field is "The {0} field is required.".

Thanks Jaime

1

There are 1 answers

0
LazZiya On

XLocalizer is using the default localization interface IStringLocalizer, so in order to use it in a static method you need to inject IStringLocalizer to your method.

public static IHtmlContent InvalidTooltipFor<TModel, TResult>(
    this IHtmlHelper<TModel> htmlhelper, 
    Expression<Func<TModel, TResult>> expression, 
    IStringLocalizer localizer)
{
    ...

    if (attribute != null) 
    {
        var localizedMsg = localizer[attribute.ErrorMessage, memberExpression.Member.Name];
        builder.AppendHtml($"<div class=\"invalid-tooltip\">{localizedMsg}</div>");
    }
    return builder;
}

Then in the caller class IStringLocalizer must be injected so you can pass it to the static method:

public class MyController {
    private readonly IStringLocalizer _localizer;
    
    public MyController(IStringLocalizer localizer)
    {
        _localizer = localizer;
    }

    public IActionResult MyMethodXYZ()
    {
        ...
        myHtmlHelper.InvalidTooltipFor<TModel, TResult>(expression, _localizer);
    }
}