繁体   English   中英

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

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

我正在使用 razor 页面创建 .net 核心 5 web 应用程序,并且正在努力将我创建到页面的多个视图组件绑定到页面上。

以下工作完美:

我的页面.cshtml:

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

我的页面.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 匹配。

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

我的页面.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>

我的页面.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>

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

有什么我缺少的东西来完成这项工作吗?

任何帮助将不胜感激!

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

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

下面是详细代码:

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

然后 model 绑定应该可以正常工作。

PS:关于使用自定义标签助手的最后说明(您可以搜索更多),不做任何事情,自定义标签助手NamedElementTagHelper将不起作用。 您最多需要在最接近您使用它的 scope 的文件_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);
   }
}

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

@{
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 更改绑定

暂无
暂无

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

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