【问题标题】:Multiple view components in .net core razor page not binding correctly.net core razor 页面中的多个视图组件未正确绑定
【发布时间】:2021-05-23 14:20:59
【问题描述】:

我正在使用 razor 页面创建一个 .net core 5 Web 应用程序,并且正在努力将我创建的视图组件绑定到我的页面 - 如果我在页面上有多个相同的视图组件。

以下完美运行:

MyPage.cshtml:

@page
@model MyPageModel
<form id="f1" method="post" data-ajax="true" data-ajax-method="post">
    <vc:my-example composite="Model.MyViewComposite1" />
</form>

MyPage.cshtml.cs

[BindProperties]
public class MyPageModel : PageModel
{
    public MyViewComposite MyViewComposite1 { get; set; }

    public void OnGet()
    {
        MyViewComposite1 = new MyViewComposite() { Action = 1 };
    }

    public async Task<IActionResult> OnPostAsync()
    {
        // checking on the values of MyViewComposite1 here, all looks good...
        // ...
        return null;
    }
}

MyExampleViewComponent.cs:

public class MyExampleViewComponent : ViewComponent
{
    public MyExampleViewComponent() { }
    public IViewComponentResult Invoke(MyViewComposite composite)
    {
        return View("Default", composite);
    }
}

Default.cshtml(我的视图组件):

@model MyViewComposite
<select asp-for="Action">
    <option value="1">option1</option>
    <option value="2">option2</option>
    <option value="3">option3</option>
</select>

MyViewComposite.cs

public class MyViewComposite
{
    public MyViewComposite() {}
    public int Action { get; set; }
}

所以到目前为止,一切都很好。我有一个下拉列表,如果我更改该下拉列表并在 OnPostAsync() 方法中检查 this.MyViewComposite1 的值,它会更改以匹配我选择的内容。

但是,我现在想在页面上有多个相同的视图组件。这意味着我现在有了这个:

MyPage.cshtml:

<form id="f1" method="post" data-ajax="true" data-ajax-method="post">
    <vc:my-example composite="Model.MyViewComposite1" />
    <vc:my-example composite="Model.MyViewComposite2" />
    <vc:my-example composite="Model.MyViewComposite3" />
</form>

MyPage.cshtml:

[BindProperties]
public class MyPageModel : PageModel
{
    public MyViewComposite MyViewComposite1 { get; set; }
    public MyViewComposite MyViewComposite2 { get; set; }
    public MyViewComposite MyViewComposite3 { get; set; }

    public void OnGet()
    {
        MyViewComposite1 = new MyViewComposite() { Action = 1 };
        MyViewComposite2 = new MyViewComposite() { Action = 1 };
        MyViewComposite3 = new MyViewComposite() { Action = 2 };
    }

    public async Task<IActionResult> OnPostAsync()
    {
        // checking on the values of the above ViewComposite items here...
        // Houston, we have a problem...
        // ...
        return null;
    }
}

我现在在页面上显示了三个下拉列表,正如我所期望的那样,当页面加载时,这三个下拉列表都正确填充。到目前为止一切顺利!

但是假设我在第一个下拉列表中选择“option3”并提交表单。我的所有 ViewComposite(MyViewComposite1、MyViewComposite2 和 MyViewComposite3)都显示相同的 Action 值,即使下拉列表都选择了不同的选项。

当我使用开发工具检查控件时,我相信我明白为什么会发生这种情况:

<select name="Action">...</select>
<select name="Action">...</select>
<select name="Action">...</select>

如您所见,呈现的是三个相同的选项,都具有相同的名称“Action”。我曾希望给他们不同的 id 可能会有所帮助,但这并没有什么不同:

<select name="Action" id="action1">...</select>
<select name="Action" id="action2">...</select>
<select name="Action" id="action3">...</select>

这显然是我正在尝试做的精简版,因为视图组件比单个下拉菜单包含更多内容,但这说明了我遇到的问题......

我缺少什么来完成这项工作吗?

任何帮助将不胜感激!

【问题讨论】:

    标签: c# asp.net-mvc asp.net-core razor-pages model-binding


    【解决方案1】:

    HTML 输出清楚地显示所有selects 都具有相同的名称Action,这将导致您遇到的问题。每个ViewComponent 都不知道其父视图模型(使用它的父视图)。所以基本上你需要以某种方式将该前缀信息传递给每个ViewComponent 并自定义name 属性的呈现方式(默认情况下,它仅受使用asp-for 影响)。

    要传递前缀路径,我们可以利用ModelExpression 作为ViewComponent 的参数。通过使用它,您可以提取模型值和路径。前缀路径可以在每个ViewComponent 的范围内共享,只能使用其ViewData。我们需要一个自定义的TagHelper 来定位所有具有asp-for 的元素,并通过在ViewData 共享的前缀前面加上前缀来修改name 属性。 这将有助于最终命名元素正确生成其name,因此模型绑定最终将正常工作。

    这里是详细代码:

    [HtmlTargetElement(Attributes = "asp-for")]
    public class NamedElementTagHelper : TagHelper
    {
        [ViewContext]
        [HtmlAttributeNotBound]
        public ViewContext ViewContext { get; set; }
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {          
            //get the name-prefix shared through ViewData
            //NOTE: this ViewData is specific to each ViewComponent
            if(ViewContext.ViewData.TryGetValue("name-prefix", out var namePrefix) &&
               !string.IsNullOrEmpty(namePrefix?.ToString()) &&
               output.Attributes.TryGetAttribute("name", out var attrValue))
            {
                //format the new name with prefix
                //and set back to the name attribute
                var prefixedName = $"{namePrefix}.{attrValue.Value}";
                output.Attributes.SetAttribute("name", prefixedName);
            }
        }
    }
    

    您需要将您的ViewComponent 修改为如下内容:

    public class MyExampleViewComponent : ViewComponent
    {
       public MyExampleViewComponent() { }
       public IViewComponentResult Invoke(ModelExpression composite)
       {
         if(composite?.Name != null){
             //share the name-prefix info through the scope of the current ViewComponent
             ViewData["name-prefix"] = composite.Name;
         }
         return View("Default", composite?.Model);
       }
    }
    

    现在使用标签助手语法使用它(注意:这里的解决方案只有在使用标签助手语法和vc:xxx标签助手时才方便,使用IViewComponentHelper的另一种方式可能需要更多代码来帮助通过ModelExpression ):

    <form id="f1" method="post" data-ajax="true" data-ajax-method="post">
      <vc:my-example composite="MyViewComposite1" />
      <vc:my-example composite="MyViewComposite2" />
      <vc:my-example composite="MyViewComposite3" />
    </form>
    

    注意对composite="MyViewComposite1" 的更改,与之前的composite="Model.MyViewComposite1" 一样。这是因为新的composite 参数现在需要ModelExpression,而不是简单的值。

    有了这个解决方案,现在你的selects 应该像这样呈现:

    <select name="MyViewComposite1.Action">...</select>
    <select name="MyViewComposite2.Action">...</select>
    <select name="MyViewComposite3.Action">...</select>
    

    然后模型绑定应该可以正常工作了。

    PS: 关于使用自定义标签助手的最后说明(您可以搜索更多),不做任何事情,自定义标签助手NamedElementTagHelper 将不起作用。您最多需要在最接近您使用它的范围的文件_ViewImports.cshtml 中添加标签助手(这里是您的ViewComponent 的视图文件):

    @addTagHelper *, [your assembly fullname without quotes]
    

    要确认标签助手NamedElementTagHelper 有效,您可以在运行包含asp-for 的任何元素的页面之前在其Process 方法中设置断点。如果它正在工作,代码应该在那里。

    更新

    借用@(Shervin Ivari) 关于ViewData.TemplateInfo.HtmlFieldPrefix 的使用,我们可以有一个更简单的解决方案,并且根本不需要自定义标签助手NamedElementTagHelper(尽管在更复杂的场景中,该解决方案是使用自定义标签助手可能更强大)。所以在这里你不需要NamedElementTagHelper 并将你的ViewComponent 更新为:

    public class MyExampleViewComponent : ViewComponent
    {
       public MyExampleViewComponent() { }
       public IViewComponentResult Invoke(ModelExpression composite)
       {
         if(composite?.Name != null){             
             ViewData.TemplateInfo.HtmlFieldPrefix = composite.Name;
         }
         return View("Default", composite?.Model);
       }
    }
    

    【讨论】:

      【解决方案2】:

      每个组件仅绑定数据,基于定义的模型,因此结果中始终具有相同名称的字段。在 razor 中,您可以将 viewdata 传递给组件。 您应该为您的组件创建自定义视图数据。

      @{
      var myViewComposite1VD = new ViewDataDictionary(ViewData);
      myViewComposite1VD.TemplateInfo.HtmlFieldPrefix = "MyViewComposite1";
      var myViewComposite2VD = new ViewDataDictionary(ViewData);
      myViewComposite2VD.TemplateInfo.HtmlFieldPrefix = "MyViewComposite2";
      var myViewComposite3VD = new ViewDataDictionary(ViewData);
      myViewComposite3VD.TemplateInfo.HtmlFieldPrefix = "MyViewComposite3";
      }
      <form id="f1" method="post" data-ajax="true" data-ajax-method="post">
      <vc:my-example composite="MyViewComposite1" view-data="myViewComposite1VD " />
      <vc:my-example composite="MyViewComposite2" view-data="myViewComposite2VD"/>
      <vc:my-example composite="MyViewComposite3" view-data="myViewComposite3VD "/>
      </form>
      

      如您所见,您可以使用 TemplateInfo.HtmlFieldPrefix 更改绑定

      【讨论】:

      • 这似乎不起作用。我是否应该在组件中以不同的方式处理视图数据?使用上面的内容并没有改变
      • @MikeLuken 这个解决方案在这里更好地使用了ViewData.TemplateInfo.HtmlFieldPrefix,我刚刚借用它并应用在我的 UPDATE 中(见我的回答),这样你就不用不需要自定义标签助手。然而,由于没有使用ModelExpression,这个答案有点长,实际上我们不需要为每个组件创建一个ViewData,因为每个组件在ViewComponent 类的上下文中已经有单独的ViewData
      • 如果您将HtmlFieldPrefix = "Model.MyViewComposite1" 更改为HtmlFieldPrefix = "MyViewComposite1"(删除Model.),此答案也将起作用,如果您更新它,我会投票赞成:) 真的我从@987654330 学到了一些东西@,至少使用过一次,但在这种情况下不知何故忘记了它。
      • 非常感谢您的回复!我会看看! :)
      • 我自己刚刚尝试过这个(我上面说的内容已调整),但看起来view-data 无法将ViewDataDictionary 作为ViewData 传递给ViewComponent。你确定view-data 可以做到吗?有没有这方面的官方文件?在使用view-data 时,我一直相信您对这个答案的信心,直到我自己尝试过,实际上我从未想过存在ViewComponent 的官方文档中未提及的隐藏view-data
      猜你喜欢
      • 1970-01-01
      • 2019-01-22
      • 2021-05-16
      • 2023-03-19
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      • 2018-02-24
      • 1970-01-01
      相关资源
      最近更新 更多