而是与foreach循环等烦心事,我会简单地用一个视图模型和编辑模板。它使生活更轻松。
因此,与视图模型开始:
public class MyViewModel
{
public IEnumerable<Type1> TheFirstList { get; set; }
}
public class Type1
{
public IEnumerable<Type2> TheSecondList { get; set; }
}
public class Type2
{
public string ThePropertyIWantToSet { get; set; }
public IEnumerable<SelectListItem> Items
{
get
{
return new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
};
}
}
}
然后控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
// filling with dummy values => those should probably
// come from your data store
var model = new MyViewModel
{
TheFirstList = Enumerable.Range(1, 2).Select(x => new Type1
{
TheSecondList = Enumerable.Range(1, 3).Select(y => new Type2())
})
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
然后对应~/Views/Home/Index.cshtml
视图:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.TheFirstList)
<input type="submit" value="OK" />
}
的~/Views/Home/EditorTemplates/Type1.cshtml
模板:
@model Type1
@Html.EditorFor(x => x.TheSecondList)
终于~/Views/Home/EditorTemplates/Type2.cshtml
模板:
@model Type2
@Html.DropDownListFor(
x => x.ThePropertyIWantToSet,
new SelectList(Model.Items, "Value", "Text")
)
现在在POST操作,你会得到一个不错的和正确绑定视图模型。编辑器模板将负责生成正确的输入字段名称。看看代码是多么简单和干净。不需要在视图中编写任何循环,担心适当的索引,只需将其留给框架即可。
谢谢!我会试试这个。 – picknick 2011-06-10 16:38:34