.net 核心剃刀页面中的多个视图组件未正确绑定

Multiple view components in .net core razor page not binding correctly

我正在使用 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 的值,它会更改以匹配我 select.

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

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;
    }
}

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

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

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

<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>

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

我是否缺少一些东西来完成这项工作?

如有任何帮助,我们将不胜感激!

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

要传递前缀路径,我们可以利用 ModelExpression 作为您的 ViewComponent 的参数。通过使用它,您可以提取模型值和路径。前缀路径可以在每个 ViewComponent 的范围内共享,仅通过使用它的 ViewData。我们需要自定义 TagHelper 来定位所有具有 asp-for 的元素,并修改 name 属性,方法是在其前面加上通过 ViewData 共享的前缀。 这将有助于最终命名元素的 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,而不是一个简单的值。

使用此解决方案,现在您的 select 应该像这样呈现:

<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);
   }
}

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

@{
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

更改绑定