1
我的场景非常复杂,所以我使用下面的示例简化了它。主要问题是绑定模型的集合属性,指定属性的路径,如Html.TextBox("List[0].Name")
而不是Html.TextBoxFor(t => t.List[0].Name)
。所以,对于目前的观点,我只会知道模型的一些元数据,所以我将不得不这样构造它。下面是这种情况:绑定模型属性集合
型号
public class ModelTest
{
public int Id {get;set;}
public List<Foo> Collection {get;set;}
}
public class Foo
{
public string Value1 {get;set;}
public string Value2 {get;set;}
}
控制器
public class TestController: Controller
{
[HttpGet]
public ActionResult Test()
{
var model = new ModelTest()
{
Id = 455,
Collection = new List<Foo>()
{
new Foo(){ Value1 = "sagasga", Value2 = "Beul"},
new Foo(){ Value1 = "dgdsgds", Value2 = "fhfhd" }
}
};
return View(model);
}
[HttpPost]
public ActionResult Test(ModelTest model)
{
//....
return View();
}
查看:
@using (Html.BeginForm())
{
@Html.TextBox("Id")
@Html.TextBox("Collection[0].Value1")
@Html.TextBox("Collection[0].Value2")
<input type="submit" value="Add" />
}
对于上面的代码,我得到了收藏价值空文本框。但是,当页面被提交时,我在Post方法中建立了正确的模型。
非常感谢, 亚历