如何在.net MVC1.0中post一个实体对象和集合对象

在MVC的开发模式下,有很多很多的特性都是非常实用的,而且解决了我们之前在Web Form的开发模式下遇到的比较痛苦的问题,今天我来谈谈Model Binder中如何POST一个一个实体对象和集合对象到服务端,欢迎砸鸡蛋或者送鲜花!
        我使用的是MVC自带的项目模板,创建一个类如下:

View Code
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}

  在View中声明的Form表单为:<% using(Html.BeginForm("aaa","Home",FormMethod.Post)){ %>

然后放置两个INPUT:

<p>姓名:<input type="text" id="user.name" name="user.name" /></p>
<p>年龄:<input type="text" id="user.age" name="user.age" /></p>

  然后在对应的Controller中创建一个Action:

View Code
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult aaa(User user,string[] cbx1)
{
return View("Index");
}

  这样当我们提交时就可以通过user对象的两个属性分别获取view中的两个表单,值得说明的是如果用户输入的年龄不是int型,那么user对象的Age属性值就为0。

       而Post一个集合对象的话如下,首先在aaa这个Action中增加一个参数List<User> users,在view中我们这么写:

View Code
<table>
<%for (int index = 0; index < 2; index++){ %>
<thead>
<tr>
<td colspan="2">用户1</td>
</tr>
</thead>
<tbody>
<tr>
<td>姓名:</td>
<td><input type="text" id="txtName1" name="users[<%= index%>].Name" /></td>
</tr>
<tr>
<td>年龄:</td>
<td>
<select id="sltAge1" name="users[<%= index%>].Age">
<option value="1">1岁</option>
<option value="10">10岁</option>
<option value="100">100岁</option>
</select>
</td>
</tr>
</tbody>
<%} %>
</table>

  提交则同样可以获取到Users的集合,值得一说的是当我给input中的name赋值为类似“users[0].Age"或“users[1].Age”时获取到的users对象的Count=1,只能用上述方式才能得到这个完整的集合对象,不知为何。

posted @ 2011-09-06 19:46  dong.net  阅读(2014)  评论(0编辑  收藏  举报