ASP .Net Core自定义标签助手将CamelCase属性转换为空格 [英] ASP .Net Core Custom Tag Helper to Convert CamelCase Properties to spaces

查看:152
本文介绍了ASP .Net Core自定义标签助手将CamelCase属性转换为空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.Net Core中,是否可以在视图模型中自动转换驼峰案例属性名称,以便在使用标签助手时在相应的标签中插入空格?

Is it possible in ASP.Net Core to automatically convert camel case property names in view models to insert spaces into the corresponding labels when using tag helpers?

如果我的视图模型如下所示。

If my view model looks like this...

[Display(Name = "First Name")]
public string FirstName { get; set; }

[Display(Name = "Last Name")]
public string LastName { get; set; }

[Display(Name = "Referral Date")]
public DateTime ReferralDate { get; set; }

似乎很多额外的配置都应用了数据注释,例如

It seems like a lot of extra configuration applying data annotations such as


[Display(Name = First name)]

[Display(Name = "First Name")]

到只需在单词之间插入一个空格。最好在默认情况下使用Tag Helper插入空格,以避免这种手动配置和可能的错字。

to simply insert a space between words. It would make sense that Tag Helpers would insert the space by default to avoid this manual configuration and potential typos.

如果不能,在这种情况下,自定义标签助手可以提供帮助

If not could a custom tag helper assist in this situation and if so how would it work?

推荐答案

您可以通过构建和注册自定义显示元数据提供程序来实现。有些库将对属性名称执行更详尽的人性化,但是您可以使用一些可靠的正则表达式来实现一些非常有用的操作。

You can achieve this by building and registering a custom display metadata provider. There are libraries that will perform more elaborate "humanization" to the property names, but you can achieve something pretty useful with some trusty regular expressions.

public class HumanizerMetadataProvider : IDisplayMetadataProvider
{
    public void CreateDisplayMetadata(DisplayMetadataProviderContext context)
    {
        var propertyAttributes = context.Attributes;
        var modelMetadata = context.DisplayMetadata;
        var propertyName = context.Key.Name;

        if (IsTransformRequired(propertyName, modelMetadata, propertyAttributes))
        {
            modelMetadata.DisplayName = () => SplitCamelCase(propertyName);
        }
    }

    private static string SplitCamelCase(string str)
    {
        return Regex.Replace(
            Regex.Replace(
                str,
                @"(\P{Ll})(\P{Ll}\p{Ll})",
                "$1 $2"
            ),
            @"(\p{Ll})(\P{Ll})",
            "$1 $2"
        );
    }

    private static bool IsTransformRequired(string propertyName, DisplayMetadata modelMetadata, IReadOnlyList<object> propertyAttributes)
    {
        if (!string.IsNullOrEmpty(modelMetadata.SimpleDisplayProperty))
            return false;

        if (propertyAttributes.OfType<DisplayNameAttribute>().Any())
            return false;

        if (propertyAttributes.OfType<DisplayAttribute>().Any())
            return false;

        if (string.IsNullOrEmpty(propertyName))
            return false;

        return true;
    }
}

IsTransformRequired 方法可确保您仍然可以在需要时使用装饰性属性覆盖提供程序。

The IsTransformRequired method ensures that you can still override the provider with a decorated property when you need to.

在启动时通过注册提供程序 IMvcBuilder 上的AddMvcOptions 方法:

Register the provider on startup through the AddMvcOptions method on IMvcBuilder:

builder.AddMvcOptions(m => m.ModelMetadataDetailsProviders.Add(new HumanizerMetadataProvider()));

这篇关于ASP .Net Core自定义标签助手将CamelCase属性转换为空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆