简体   繁体   English

使用局部视图对集合属性进行模型绑定

[英]Model binding a collection property with a partial view

Suppose I have a model like this: 假设我有这样的模型:

public class Foo {
    public List<Bar> Bars { get; set; }
    public string Comment { get; set; }
}

public class Bar {
    public int Baz { get; set; }
}

And I want a view of Foo that lets users edit Bar items. 我想要一个Foo视图,让用户可以编辑Bar项目。 But with a catch: I want the Bar editing to be handled by a partial view. 但有一个问题:我希望Bar编辑由部分视图处理。

@model Web.ViewModels.Foo

@using(Html.BeginForm()) {
    @Html.Partial("_EditBars", Model.Bars)
    @Html.TextAreaFor(m => m.Comment)
    ...
}

The _EditBars partial view looks something like: _EditBars局部视图看起来像:

@model List<Web.ViewModels.Bar>

@for (int i = 0; i < Model.Count; i++) {
    @Html.EditorFor(m => Model[i].Baz)
}

I want this to model bind to my action, which looks something like: 我希望这个模型绑定到我的动作,看起来像:

[HttpPost]
public ActionResult Edit(Foo foo) {
    // Do stuff
}

Unfortunately, this is the data that I'm posting, which doesn't model bind the Bars property: 不幸的是,这是我发布的数据,它没有模型绑定Bars属性:

[1].Baz=10&[0].Baz=5&Comment=bla

It makes sense that this doesn't work, because it's missing the Bars prefix. 这是不合理的,因为它缺少Bars前缀。 If I understand correctly, I need it to be this: 如果我理解正确,我需要它是这样的:

Bars[1].Baz=10&Bars[0].Baz=5&Comment=bla

So, I tried this approach : 所以,我尝试了这种方法

@Html.Partial(
    "_EditBars",
    Model.Bars,
    new ViewDataDictionary(ViewData)
    {
        TemplateInfo = new TemplateInfo
        {
            HtmlFieldPrefix = "Bars"
        }
    }) 

But that's not working either. 但那也没有用。 With that, I'm getting: 有了这个,我得到:

Bars.[1].Baz=10&Bars.[0].Baz=5&Comment=bla

I assume that that isn't working because of the extra period ( Bars.[1] vs. Bars[1] ). 我认为这是因为额外的时期( Bars.[1] vs. Bars[1] )不起作用。 Is there anything I can do to get the result that I desire? 我有什么办法可以得到我想要的结果吗?

Note: This is a major oversimplification of my actual situation. 注意:这是我实际情况的一个主要过分简化。 I recognize that with something this simple, the best approach would probably be to make an EditorTemplate for Bar and loop through using EditorFor in my view. 我认识到,通过这种简单的方法,最好的方法可能是为Bar创建一个EditorTemplate ,并在我的视图中使用EditorFor进行循环。 If possible, I'd like to avoid this solution. 如果可能的话,我想避免这个解决方案。

As you do not want to use an EditorTemplate for Bar , a solution of your scenario could be: 由于您不想使用EditorTemplate for Bar ,因此您的方案的解决方案可能是:

Change the @model type of the '_EditBars' partial view to Foo and view should be like: 将'_EditBars'局部视图的@model类型更改为Foo ,视图应如下所示:

@model Foo

@if (Model.Bars != null)
{
    for (int i = 0; i < Model.Bars.Count; i++)
     {
         @Html.EditorFor(m => Model.Bars[i].Baz)
     }
}

(It would be better to change the partial view's name to '_EditFooBars' ) (将部分视图的名称更改为'_EditFooBars'会更好)

Hope this helps. 希望这可以帮助。

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

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