[英]Binding to a List property of a Model
我有以下型号
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语法的引用。
提前致谢
这应该使您入门。
您的型号:
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()操作,您可以在其中执行任何操作。 在我的示例中,它将显示第二个“名称”文本框中输入的内容。 您显然可以遍历每个值并检查是否填写等。例如
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
。但这显然取决于您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.