【问题标题】:ASP.Net Core 3.1 MVC custom tag helper condition attribute is always falseASP.Net Core 3.1 MVC 自定义标签助手条件属性始终为 false
【发布时间】:2020-10-06 05:14:18
【问题描述】:

我为我的网络应用程序中的选择元素创建了一个标签助手:

[HtmlTargetElement( "select", Attributes = nameof( AutoPostBack ) )]
    public class AutoPostBackTagHelper : TagHelper
    {
        public bool AutoPostBack { get; set; }

        public override void Process( TagHelperContext context, TagHelperOutput output )
        {
            // AutoPostBack is always false
            if ( AutoPostBack )
            {
                output.Attributes.SetAttribute( "onchange", "this.form.submit();" );
            }

            // here I could extract the attribute
            Microsoft.AspNetCore.Html.HtmlString x =
                (Microsoft.AspNetCore.Html.HtmlString)context.AllAttributes[nameof( AutoPostBack )].Value;
            // and this is working
            if ( x.Value == "true" )
            {
                output.Attributes.SetAttribute( "onchange", "this.form.submit();" );
            }
        }
    }

这是我认为的用法:

<select asp-for="MessageType"
    asp-items="Html.GetEnumSelectList<MyViewModels.MessageType>()"
    class="form-control" AutoPostBack="true">
</select>

我想使用通过定义的属性AutoPostBack推荐的条件。为什么属性总是假的?

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-core tag-helpers


    【解决方案1】:

    为了获得 AutoPostBack 参数集,您需要将其传递给 'kebab-case' 中的标签助手。

    查看此示例中的注释:https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/authoring?view=aspnetcore-3.1#setattribute-and-setcontent

    我认为如果你使用它会起作用

    <select auto-post-back="true"></select>
    
    [HtmlTargetElement("select", Attributes = "auto-post-back")]
        public class AutoPostBackTagHelper : TagHelper
        {
            public bool AutoPostBack { get; set; }
    
            public override void Process(TagHelperContext context, TagHelperOutput output)
            {
                // Will hopefully work :-)
                if (AutoPostBack)
                {
                    output.Attributes.SetAttribute("onchange", "this.form.submit();");
                }
            }
        }
    

    【讨论】:

    • 感谢您的回答。那行得通。一开始我没有意识到你写的属性名没有nameof。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多