绑定到模型的List属性

本文关键字:List 属性 模型 绑定 | 更新日期: 2023-09-27 18:21:45

我有以下型号的

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

我想创建一个视图,让用户能够CRUDFoos。

现有研究

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

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

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

要求
我希望能够绑定到这个复杂的模型,这样它就可以完整地传递给控制器。假设控制器什么也不做,只是渲染视图并在发布时接收FooController模型。此外,我希望任何相关的文章或对View语法的引用都能实现这一点。

提前感谢

绑定到模型的List属性

这应该会让您开始。

您的型号:

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

这里发生的是,当你按下submit时,iList将被发送到你的HttpPost Foo()操作,在那里你可以用它做任何你想做的事情。在我的例子中,它将显示输入第二个Name文本框的内容。很明显,你可以循环浏览每个值,并检查是否填写等。例如

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

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