在 ASP.Net Core 中,使用标签助手时是否可以自动转换视图模型中的驼峰式大小写属性名称,以将空格插入到相应的标签中?
如果我的视图模型看起来像这样......
[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; }
似乎有很多应用数据注释的额外配置,例如
[显示(名称=“名字”)]
只需在单词之间插入空格即可。默认情况下,标记帮助程序会插入空格以避免这种手动配置和潜在的拼写错误,这是有道理的。
如果没有,自定义标签助手可以在这种情况下提供帮助吗?如果可以的话,它将如何工作?
如果你只关心label,您可以轻松覆盖标签标签助手.
[HtmlTargetElement("label", Attributes = "title-case-for")]
public class TitleCaseTagHelper : LabelTagHelper
{
public TitleCaseTagHelper(IHtmlGenerator generator) : base(generator)
{
}
[HtmlAttributeName("title-case-for")]
public new ModelExpression For { get; set; }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
if (context == null)
throw new ArgumentNullException("context");
if (output == null)
throw new ArgumentNullException("output");
string name = For.ModelExplorer.Metadata.DisplayName ?? For.ModelExplorer.Metadata.PropertyName;
name = name.Humanize(LetterCasing.Title);
TagBuilder tagBuilder = this.Generator.GenerateLabel(
this.ViewContext,
this.For.ModelExplorer,
this.For.Name,
name,
(object) null);
if (tagBuilder == null)
return;
output.MergeAttributes(tagBuilder);
if (output.IsContentModified)
return;
TagHelperContent childContentAsync = await output.GetChildContentAsync();
if (childContentAsync.IsEmptyOrWhiteSpace)
output.Content.SetHtmlContent((IHtmlContent) tagBuilder.InnerHtml);
else
output.Content.SetHtmlContent((IHtmlContent) childContentAsync);
}
}
Usage
<label title-case-for="RememberMe" class="col-md-2 control-label"></label>
请确保放置使用语句 and @addTagHelper inside _ViewImports.cshtml.
@using YourNameSpace.Helpers
@addTagHelper *, YourNameSpace
Note
I use 人性化者 https://github.com/Humanizr/Humanizer仅英文 NuGet 包 -人性化核心 https://www.nuget.org/packages/Humanizer.Core。它比我自己编写的方法更健壮。如果您不喜欢开销,则可以使用正则表达式。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)