MVC3 Razor httppost返回复杂对象的子集合 [英] MVC3 Razor httppost return complex objects child collections

查看:175
本文介绍了MVC3 Razor httppost返回复杂对象的子集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有长时间使用MVC3并且认为这是我所知道的一个缺陷,而不是真正的问题。

I have not been using MVC3 for that long and think this is a flaw in my knowledge than a real issue.

我有一个基本有一些基础的对象属性,然后是内部对象的集合,(简化版):

I have an object that has a few basic properties and then a collection of inner objects, (simplified version):

public class myClass
{
    public string Name { get; set; }
    public string Location { get; set; }
    public List<myOtherClass> Children { get; set; }
 }

public class myOtherClass
{
    public string Name { get; set; }
    public int Age { get; set; }
}

我有一个强类型为myClass对象的视图。我使用@ html.editorfor作为名称和位置,然后使用foreach作为子对象。在foreach中,我再次为每个属性使用editorfor。

I have a view that is strongly typed to the "myClass" object. I use the @html.editorfor for the name and location then a foreach for the children objects. in the foreach I again use editorfor's for each of their properties.

在回发(httppost动作)上填写myClass名称和位置,但子列表为空。

On postback(httppost action) the myClass name and location are filled out but the children list is empty.

我不确定如何制作视图以确保它填充所有子元素。

I am not sure how I should craft the view to ensure it populates all the child elements.

我试过两者:

[httppost]
public actionresult myaction(myClass myclass)
{
}

和:

[httppost]
public actionresult myaction()
{
    myClass myclass = new myClass();
    TryUpdateModel(myclass);
}


推荐答案

你不应该迭代孩子手动,您应该为 myOtherClass 定义编辑器模板,然后让框架为所有项目集合生成编辑器。

You should not iterate over children manually, you should define editor template for myOtherClass and then just let framework generate editors for all items collection.

创建EditorTemplate为 myOtherClass at 〜/ Views / Shared / EditorTemplates / myOtherClass.cshtml

Create EditorTemplate for myOtherClass at ~/Views/Shared/EditorTemplates/myOtherClass.cshtml

@model myOterClass
@Html.EditorFor(model => model.Name)
@Html.EditorFor(model => model.Age)

然后在父视图中

@Html.EditorFor(model => model.Children)

这将在内部调用集合中所有项目的编辑器模板,并为模型绑定生成正确的输入名称。

This will internally call your editor template for all items in collection, and generate correct input names for model binding.

这篇关于MVC3 Razor httppost返回复杂对象的子集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆