問題描述
在 Core MVC 中,有一個新概念,即標簽助手.
In Core MVC there is anew concept as Tag helpers.
我們之前可以創建自定義 html 幫助器,以根據驗證數據注釋附加一些類,例如 [Required].
We could previously create custom html helpers to attach some classes based on the validation data annotations such as [Required].
作為 TagHelpers arq 相當新的領域,我找不到足夠的資源來實現以下目標:
As TagHelpers arq quite new area I cannot find anough resources to achieve the following:
這是視圖模型:
[Required]
public Gender Gender { get; set; }
查看:
<label class="control-label col-md-3 required" asp-for="Gender"></label>
css:
.required:after {
content: "*";
font-weight: bold;
color: red;
}
輸出:
但我不想在標簽中手動添加所需的 css 類.不知何故,我應該能夠擴展 LabelTagHelper 以讀取模型數據注釋,如果它具有 [Required] 然后在標簽元素中添加所需的類.
But I don't want to manully add the required css class in the label. Somehow I shoudl be able to extend the LabelTagHelper to read model data annotations and if it has the [Required] then add required class in the label element.
謝謝,
推薦答案
是的,您可以通過從 LabelTagHelper
類繼承并首先將您自己的類添加到屬性列表中來輕松擴展它.
Yup, you can extend this pretty easily by inheriting from the LabelTagHelper
class and adding in your own class to the attribute list first.
[HtmlTargetElement("label", Attributes = "asp-for")]
public class RequiredLabelTagHelper : LabelTagHelper
{
public RequiredLabelTagHelper(IHtmlGenerator generator) : base(generator)
{
}
public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
if (For.Metadata.IsRequired)
{
CreateOrMergeAttribute("class", "required", output);
}
return base.ProcessAsync(context, output);
}
private void CreateOrMergeAttribute(string name, object content, TagHelperOutput output)
{
var currentAttribute = output.Attributes.FirstOrDefault(attribute => attribute.Name == name);
if (currentAttribute == null)
{
var attribute = new TagHelperAttribute(name, content);
output.Attributes.Add(attribute);
}
else
{
var newAttribute = new TagHelperAttribute(
name,
$"{currentAttribute.Value.ToString()} {content.ToString()}",
currentAttribute.ValueStyle);
output.Attributes.Remove(currentAttribute);
output.Attributes.Add(newAttribute);
}
}
}
這篇關于TagHelpers 基于驗證屬性為 LabelTagHelper 添加自定義類 [必需]的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!