原来以为 MVC自动绑定模型不能 直接转化为LIST,经过测试之后。发现我错了。是可以的。不用再转成数组再转为LIST。省了一大步。呵呵
1.首先,创建一个MVC4的项目
2.创建一个Controller(控制器),有些小小菜肯定也知道Home是路由里默认的。
3.控制器都有了,默认会有个Index动作方法,我们只需要在拷贝一个接受Post请求的action即可
1
2
3
4
5
6
7
8
9
10
11
12
|
public ActionResult
Index() { return View(); } [HttpPost] //视图中加的是实体类中的属性名对应 //集合模型,视图为动作方法参数名字[索引].属性名 public ActionResult
Index(List<Student> stu) { return View(); } |
为了压缩例子,这里直接就动用集合,这里有个测试类中犹如【小明】般存在的类Student,我们来看它的结构
1
2
3
4
5
6
7
8
9
10
11
12
|
public class Student { public int Id
{ get ; set ;
} public string Name
{ get ; set ;
} public StudentExt
Stu { get ; set ;
} } public class StudentExt { public string Address
{ get ; set ;
} } |
好简单吧,我们只是做测试而已,足够了。当我们有了方法和模型了以后,我们需要用一个视图来装载这个模型。添加个视图。
当我们有了视图以后,我们要在里面增加模型的属性,以便在提交表单的时候Action能接收到模型数据。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@{ ViewBag.Title
= "Index"; } @using
(Html.BeginForm("Index")) { @Html.TextBox("stu[0].Id")
@*注释,stu代表action的参数名,由于该参数是集合[0]代表第一项,Id代表它的属性,大写的Stu代表stu的属性,Address代表Stu的属性*@< br >
@Html.TextBox("stu[0].Name") @Html.TextBox("stu[0].Stu.Address"); < br /> @Html.TextBox("stu[1].Id") @Html.TextBox("stu[1].Name") @Html.TextBox("stu[1].Stu.Address"); < br /> < input type="submit"
value="测试简单模型" /> } |
我们来运行一下看看效果,当我们点击测试简单模型时,注意点之前注意打个断点以便观察这样是否能拿到模型。
我真点了- -,来看拿到什么了吧!
测试完毕,成功拿到模型数据。