在ASP.NET MVC Core中,您可以使用新的Tag Helpers,这会使您的HTML看起来像... HTML :)
像这样:
<div class="form-group row">
<label asp-for="Name" class="col-md-2 form-control-label"></label>
<div class="col-md-10">
<input asp-for="Name" class="form-control" aria-describedby="Name-description" />
<span asp-description-for="Name" class="form-text text-muted" />
<span asp-validation-for="Name" class="text-danger" />
</div>
</div>
注意1:您可以aria-describedby
在输入元素中使用属性,因为ID将在带有asp-description-for
属性的span元素中自动创建。
注2:在引导4类form-text
和text-muted
替换V3help-block
块级帮助文本类。
为了使这种魔术发生,您只需要创建一个新的Tag Helper:
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
[HtmlTargetElement("span", Attributes = DescriptionForAttributeName)]
public class SpanDescriptionTagHelper : TagHelper
{
private const string DescriptionForAttributeName = "asp-description-for";
public SpanDescriptionTagHelper(IHtmlGenerator generator)
{
Generator = generator;
}
public override int Order
{
get
{
return -1000;
}
}
[HtmlAttributeNotBound]
[ViewContext]
public ViewContext ViewContext { get; set; }
protected IHtmlGenerator Generator { get; }
[HtmlAttributeName(DescriptionForAttributeName)]
public ModelExpression DescriptionFor { get; set; }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
var metadata = DescriptionFor.Metadata;
if (metadata == null)
{
throw new InvalidOperationException(string.Format("No provided metadata ({0})", DescriptionForAttributeName));
}
output.Attributes.SetAttribute("id", metadata.PropertyName + "-description");
if( !string.IsNullOrWhiteSpace( metadata.Description))
{
output.Content.SetContent(metadata.Description);
output.TagMode = TagMode.StartTagAndEndTag;
}
}
}
并使您的标签助手对我们所有的Razor视图都可用。将addTagHelper指令添加到Views/_ViewImports.cshtml
文件中:
@addTagHelper "*, YourAssemblyName"
注意1:替换YourAssemblyName
为项目的程序集名称。
注意2:对于您的所有标记助手,您只需执行一次即可!
有关标签帮助程序的更多信息,请访问:https :
//docs.asp.net/zh/latest/mvc/views/tag-helpers/intro.html
而已!享受新的Tag Helpers的乐趣!