ASP.Net Core 3.1 MVC 自定义标签助手条件属性始终为 false
ASP.Net Core 3.1 MVC custom tag helper condition attribute is always false
我在我的 Web 应用程序中为 select 个元素创建了一个标签助手:
[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 推荐的条件。为什么属性总是 false?
为了获取 AutoPostBack 参数集,您需要将其传递给 'kebab-case' 中的标签助手。
我想如果你使用这个它会起作用
<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();");
}
}
}
我在我的 Web 应用程序中为 select 个元素创建了一个标签助手:
[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 推荐的条件。为什么属性总是 false?
为了获取 AutoPostBack 参数集,您需要将其传递给 'kebab-case' 中的标签助手。
我想如果你使用这个它会起作用
<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();");
}
}
}