1

我有以下型号

public class FooContainer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public IList<Foo> Foos { get; set; }
}

public class Foo
{
    public string Name {get; set; }
    public string Description {get; set;}
}

示例控制器

public class FooController : Controller
{
    public ActionResult Index(){
        return View(new FooContainer());
    }

    [HttpPost]
    public ActionResult Index(FooContainer model){
        //Do stuff with the model
    }
}

我想创建一个视图,使用户能够 CRUD Foos。

现有研究

我已阅读以下内容:http:
//haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx http://haacked.com/archive/2008/10/23/model -binding-to-a-list.aspx

连同以下 SO 文章
MVC4 允许用户编辑列表项
MVC4 将模型绑定到 ICollection 或部分列表

所以我知道如何来回传递 IEnumerable<>,问题是我想传递一些容器,其他属性包括IEnumerable<>

要求
我希望能够绑定到这个复杂的模型,以便将其完全完整地传递给控制器​​。假设控制器只渲染视图并在发布时接收 FooController 模型。此外,我想要启用此功能所需的任何相关文章或对 View 语法的引用。

提前致谢

4

1 回答 1

2

这应该让你开始。

您的型号:

public class FooContainer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public IList<Foo> Foos { get; set; }
}

public class Foo
{
    public string Name {get; set; }
    public string Description {get; set;}
}

您的控制器操作:

[HttpGet]
public ActionResult Foo()
{
    var model = new FooContainer();
    return View("Foo", model);
}

[HttpPost]
public ActionResult Foo(FooContainer model)
{
    ViewBag.Test = m.Foos[1].Name;
    return View("Foo", model);
}

您的看法:

@model DriveAway.Web.Models.FooContainer

@using(Html.BeginForm()) 
{
    <p>@Html.TextBoxFor(m => m.ID)</p>
    <p>@Html.TextBoxFor(m => m.Name)</p>   

    for (int i = 0; i < 5; i++)
    {
        <p>@Html.TextBoxFor(m => m.Foos[i].Name)</p>
        <p>@Html.TextBoxFor(m => m.Foos[i].Description)</p>
    }

    <button type="submit">Submit</button>

}

@ViewBag.Test

这里发生的情况是,当您按下提交时,iList 将被发送到您的 HttpPost Foo() 操作,您可以在那里做任何您想做的事情。在我的示例中,它将显示输入到第二个名称文本框中的任何内容。您显然可以遍历每个值并检查是否填写等。例如

foreach (var f in m.Foos)
   if (!string.IsNullOrEmpty(f.Name) && !string.IsNullOrEmpty(f.Description))
       addToDB(f); // some method to add to to a database

在视图中,我使用for loop了限制为 5 的 a。但这显然取决于您。

于 2013-07-09T01:13:06.183 回答