【问题标题】:Using DataAnnotation localizer in your extension method for HtmlHelper in ASP.net core mvc 3.1在 ASP.net core mvc 3.1 中的 HtmlHelper 扩展方法中使用 DataAnnotation 本地化器
【发布时间】:2020-08-08 09:35:39
【问题描述】:

我希望对 HTML Helper 进行扩展,以显示我的 ViewModel 属性的描述。这是列表,因为自从How do I display the DisplayAttribute.Description attribute value? 以来,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 不要求额外的参数时,它不是很好的解决方案。

【问题讨论】:

    标签: c# localization asp.net-core-mvc data-annotations asp.net-core-3.1


    【解决方案1】:

    您只需要获得对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];
        }
    }
    

    如果你想要更多的控制,我建议你从 ASP.NET Core 内部的工作中获得一些想法,by taking a look at the source code (method CreateDisplayMetadata)

    【讨论】:

    • 谢谢!我有自己的 IStringLocalizerFactory 将类型转换为合适的资源位置,因为资源文件位置的默认约定对我的项目来说不是很舒服。所以我改变了方法:description = _LocalizerFactory.Create(memberExpression.Expression.Type)[description];
    猜你喜欢
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多