模型将集合属性与局部视图绑定 [英] 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; }
}
我想要一个Foo
的视图,该视图允许用户编辑Bar
项.但是有一个要注意的地方:我希望Bar
的编辑可以通过局部视图来处理.
And I want a view of Foo
that lets users edit Bar
items. But with a catch: I want the Bar
editing to be handled by a partial view.
@model Web.ViewModels.Foo
@using(Html.BeginForm()) {
@Html.Partial("_EditBars", Model.Bars)
@Html.TextAreaFor(m => m.Comment)
...
}
_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
}
不幸的是,这是我要发布的数据,没有模型绑定Bars
属性:
Unfortunately, this is the data that I'm posting, which doesn't model bind the Bars
property:
[1].Baz=10&[0].Baz=5&Comment=bla
这是行不通的,因为它缺少Bars
前缀.如果我理解正确,我就需要这样:
It makes sense that this doesn't work, because it's missing the Bars
prefix. If I understand correctly, I need it to be this:
Bars[1].Baz=10&Bars[0].Baz=5&Comment=bla
因此,我尝试了此方法:
@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
我认为由于额外的时间段(Bars.[1]
vs. Bars[1]
),这无法正常工作.我可以做些什么来获得想要的结果吗?
I assume that that isn't working because of the extra period (Bars.[1]
vs. Bars[1]
). Is there anything I can do to get the result that I desire?
注意:这是我实际情况的一个过分简化.我认识到,使用这种简单的方法,最好的方法可能是为Bar
创建一个EditorTemplate
并在我的视图中使用EditorFor
循环.如果可能的话,我想避免这种解决方案.
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. If possible, I'd like to avoid this solution.
推荐答案
由于您不想对Bar
使用EditorTemplate
,因此您的方案可以是:
As you do not want to use an EditorTemplate
for Bar
, a solution of your scenario could be:
将"_EditBars"局部视图的@model类型更改为Foo
,该视图应类似于:
Change the @model type of the '_EditBars' partial view to Foo
and view should be like:
@model Foo
@if (Model.Bars != null)
{
for (int i = 0; i < Model.Bars.Count; i++)
{
@Html.EditorFor(m => Model.Bars[i].Baz)
}
}
(最好将部分视图的名称更改为'_EditFooBars'
)
(It would be better to change the partial view's name to '_EditFooBars'
)
希望这会有所帮助.
这篇关于模型将集合属性与局部视图绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!