Mvc中把list从View传入Controller
public class User { public string Name { get; set; } public bool IsChecked { get;set;} public int Age { get; set; } } [HttpGet] public ActionResult Index() { var list = new List<User>() { new User() {Name = "hky", IsChecked = true, Age = 1}, new User() {Name = "ds", IsChecked = true, Age = 1}, new User() {Name = "dsdasd", IsChecked = true, Age = 1}, }; return View(list); } [HttpPost] public ActionResult Index(List<User> list) { return View(); }
@model List<MvcApplication1.Controllers.User> @{ Layout = null; } <!DOCTYPE html> <html> <head> <title>Index</title> </head> <body> @using (Html.BeginForm()) { for (int i = 0; i < Model.Count; i++) { @Html.TextBoxFor(x => Model[i].Name) } <input type="submit" name="name" value=" 提交 "/> } </body> </html>
通过谷歌查看源代码如下:
是通过索引的形式来命名name,如果不是这种形式传值将不成功,至少我实验的是这样的,这个点我实验的时候也一直很奇怪为何后台用foreach的方式却无法接收
@using (Html.BeginForm()) { foreach (var item in Model) { @Html.TextBoxFor(x => item.Name) } <input type="submit" name="name" value=" 提交 "/> }
生成的html代码如下:
我个人实验在后台始终无法接收到值