简体   繁体   English

Razor Pages Custom Tag Helper 2 Way Bind

[英]Razor Pages Custom Tag Helper 2 Way Bind

I am wanting to create a custom tag helper in razor pages which binds to a custom model but the value is not being read back into the modal on post, below is my TagHelper code我想在 razor 页面中创建一个自定义标签助手,该页面绑定到自定义 model 但该值没有被读回帖子中的模式,下面是我的 TagHelper 代码

[HtmlTargetElement("kenai-date", TagStructure = TagStructure.WithoutEndTag)]
public class Date : TagHelper
{
    //public string Value { get; set; }

    public ModelExpression AspFor { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "input";
        output.TagMode = TagMode.SelfClosing;
        output.Attributes.Add("value", this.AspFor.Model);

    }
}

I am using the TagHelper with the below code我正在使用带有以下代码的 TagHelper

<kenai-date asp-for="DateValue" />

'DateValue' is a public property on the page, when first rendering the page the value of DateValue is correctly visible in the TagHelper Input element, if I force an OnPost, the value is removed. 'DateValue' 是页面上的公共属性,当第一次呈现页面时,DateValue 的值在 TagHelper 输入元素中正确可见,如果我强制 OnPost,则删除该值。

I have applied the same to a standard input element with asp-for set and that works fine so suspect I am missing something in my TagHelper.我已将其应用于带有 asp-for 集的标准输入元素,并且工作正常,因此怀疑我在 TagHelper 中遗漏了一些东西。

Asp.net core bind model data with name attribute.You use a custom tag helper,so it will get html like <input value="xxx"> .So when form post,you cannot bind model data with name attribute,and when return Page in OnPost handler,model data is null.You need to add name attribute to <kenai-date asp-for="DateValue" /> .Here is a demo: Asp.net core bind model data with name attribute.You use a custom tag helper,so it will get html like <input value="xxx"> .So when form post,you cannot bind model data with name attribute,and when return Page in OnPost handler,model 数据为 null。您需要在<kenai-date asp-for="DateValue" />中添加 name 属性。这是一个演示:

TestCustomTagHelper.cshtml: TestCustomTagHelper.cshtml:

<form method="post">
    <kenai-date asp-for="DateValue" name="DateValue" />
    <input type="submit" />
</form>   

TestCustomTagHelper.cshtml.cs: TestCustomTagHelper.cshtml.cs:

public class TestCustomTagHelperModel : PageModel
    {
        [BindProperty]
        public string DateValue { get; set; }
        public void OnGet()
        {
            DateValue = "sss";
        }
        public IActionResult OnPost()
        {
            
            return Page();
        }
    }

result:结果: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM