【问题标题】:Tag helper not being processed in ASP.NET Core 2标签助手未在 ASP.NET Core 2 中处理
【发布时间】:2018-03-31 04:48:19
【问题描述】:

我添加了以下标签助手:

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-fork-error-class 按原样转发到生成的页面(而不是将 has-danger 类添加到 class 属性)。

我做错了什么?

【问题讨论】:

  • 我在 Mac OS X 上,所以通过 dotnet 控制台/终端应用程序。打电话给dotnet build/dotnet run

标签: c# asp.net .net asp.net-core asp.net-core-2.0


【解决方案1】:

注册 Tag Helpers 时,需要的是 程序集,而不是命名空间 - 在 docs 中解释。

...第二个参数“Microsoft.AspNetCore.Mvc.TagHelpers”指定包含标签助手的程序集。 Microsoft.AspNetCore.Mvc.TagHelpers 是内置 ASP.NET Core Tag Helpers 的程序集。

所以在你的情况下,你可以改变这个:

@addTagHelper *, X.TagHelpers

到这里:

@addTagHelper *, X

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2019-04-02
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多