我已经添加了以下标签助手:
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace X.TagHelpers
{
[HtmlTargetElement(Attributes = ValidationForAttributeName + "," + ValidationErrorClassName)]
public class ValidationClassTagHelper : TagHelper
{
private const string ValidationForAttributeName = "k-validation-for";
private const string ValidationErrorClassName = "k-error-class";
[HtmlAttributeName(ValidationForAttributeName)]
public ModelExpression For { get; set; }
[HtmlAttributeName(ValidationErrorClassName)]
public string ValidationErrorClass { get; set; }
[HtmlAttributeNotBound]
[ViewContext]
public ViewContext ViewContext { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
Console.WriteLine("\n\n------------!!!!!!---------\n\n");
ModelStateEntry entry;
ViewContext.ViewData.ModelState.TryGetValue(For.Name, out entry);
if (entry == null || !entry.Errors.Any()) return;
var tagBuilder = new TagBuilder(context.TagName);
tagBuilder.AddCssClass(ValidationErrorClass);
output.MergeAttributes(tagBuilder);
}
}
}
然后在_ViewImports.cshtml
中添加了以下代码行:
@addTagHelper *, X.TagHelpers
文件已经正确编译,如果我引入语法错误,则
dotnet build
会对其进行警告。然后,在我的一个页面中添加以下内容:
<div k-validation-for="OldPassword" k-error-class="has-danger"></div>
如果我加载页面,服务器端没有控制台输出,并且
k-validation-for
和 k-error-class
被原样转发到生成的页面(而不是将 has-danger
类添加到 class
属性中)。我做错了什么?
dotnet
控制台/终端应用程序来执行。调用dotnet build
/dotnet run
命令。 - Shoe