MVC 参数如何自动绑定数组对象

在View页面有多行数据,针对每一行数据都可以进行编辑,编辑之后的结果需要提交到服务器端。这个功能的实现在以往的.net框架很好实现,通过结合js就能达到目的,可如果现在在mvc框架下也用js辅助,Controller层和View层的分离就不是那么理想了,破坏了整个架构的理念。

为了让Controller层与View层之间不那么相互依赖,其实还是有办法实现这个提交多行数据的功能的,就是大家都依赖于Model层对象。可怎么实现呢,开始想了好久都没有想出来,确实让人棘手。在网上查看相关资料,呵呵,既然能找到。具体实现如下:

说明:CustomSetting是Model层的一个Entity类。
注意:
(1)下面Controller的方法中的参数名称要跟View中的控件名称对应上;
(2)控件名称:方法中的参数名称+"[数组下标]"+".Entity类的属性名称"

在Controller中的方法:
        [Authorize]
        [HttpPost]
        public ActionResult Setting(IList<CustomSetting> item)
        {
            ...
            Entities db = new Entities();
            foreach (CustomSetting t in item)
            {
                ...
            }
            db.SaveChanges();

            return View("Index");
        }
在View中的页面:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<PortalNews.Models.CustomSetting>>" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Setting</title>
    <link href="/Content/apply.css" rel="Stylesheet" type="text/css" />
</head>
<body>
    <% using (Html.BeginForm())
       {%>
    <%: Html.ValidationSummary(true) %>
    <table cellpadding="0" cellspacing="1" border="0">
        <tbody>
            <tr>
                <th>
                    Area
                </th>
                <th width="10%" align="left">
                    Show
                </th>
                <th width="60%" align="left">
                    DisplayOrder
                </th>
            </tr>
            <% int i = 0; foreach (var item in Model)
               { %>
            <tr>
                <td>
                    <%: Html.Hidden("item["+ i.ToString()+"].FormID", item.FormID)%>
                    <%: item.FormName%>
                </td>
                <td>
                    <%if (item.Disabled)
                      { %>
                    <%: Html.CheckBox("item[" + i.ToString() + "].Show", item.Show == "Y", new { disabled = "true" })%><%}
                      else
                      {%>
                    <%: Html.CheckBox("item[" + i.ToString() + "].Show", item.Show == "Y")%>
                    <%} %>
                </td>
                <td>
                    <%: Html.TextBox("item[" + i.ToString() + "].DisplayOrder", item.DisplayOrder, new { size = "5" })%>
                </td>
            </tr>
            <% i++;
               } %>
        </tbody>
    </table>
    <p>
        <input type="submit" value="Save" class="inputBtn" />
    </p>
    <% } %>
</body>
</html>

posted @ 2011-11-11 19:45  linyujade  阅读(372)  评论(0编辑  收藏  举报