0

基于: MVC Html.CheckBox 和表单提交问题

让我们考虑以下示例。看法:

   <% using(Html.BeginForm("Retrieve", "Home")) %>
       <% { %>
    <%foreach (var app in newApps)              { %>  
  <tr> 
       <td><%=Html.CheckBox(""+app.ApplicationId )%></td>      

   </tr>  
<%} %>
 <input type"submit"/>
<% } %>

控制器:

 List<app>=newApps; //Database bind
 for(int i=0; i<app.Count;i++)
 {

    var checkbox=Request.Form[""+app[i].ApplicationId];
    if(checkbox!="false")// if not false then true,false is returned
 }

提出的解决方案是关于手动解析 Request.Form 对我来说似乎超出了 MVC 概念。它在对该控制器方法进行单元测试时出现问题。在这种情况下,我需要生成模拟 Request.Form 对象,而不是作为输入参数传递的一些 ViewModel。

问:有没有其他类似的提交表单的解决方案,以便包含提交的控件集合的 ViewModel 对象作为输入参数传递给控制器​​方法?

例如:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Retrieve(AppList[] applist) 

或者

public ActionResult Retrieve(AppList<App> applist) 

ETC

4

1 回答 1

0

控制器:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Retrieve(AppList[] applist)

看法:

<% using(Html.BeginForm("Retrieve", "Home")) %> { %>
    <%foreach (var app in newApps) { %>
    <tr>
        <td><%=Html.CheckBox(String.Format("appList[{0}].AProperty", app.ApplicationId) %></td>
    </tr>
    <% } %>
    <input type"submit" />
<% } %>

阅读:Scott Hanselman 的 ComputerZen.com - 用于模型绑定到数组、列表、集合、字典的 ASP.NET 有线格式

更新:

如果 ApplicationId 是来自 DB 的键,则最好AppList<App>用作 Action 参数。那么您的表格将如下所示:

<% using(Html.BeginForm("Retrieve", "Home")) %> { %>
<% var counter = 0; %>
    <% foreach (var app in newApps) { %>
    <tr>
        <td><%=Html.CheckBox(String.Format("appList[{0}].Key", counter), app.ApplicationId) %></td>
        <!-- ... -->
        <td><%=Html.Input(String.Format("appList[{0}].Value.SomeProperty1", counter), app.SomeProperty1) %></td>
        <td><%=Html.Input(String.Format("appList[{0}].Value.SomePropertyN", counter), app.SomePropertyN) %></td>
        <% counter = counter + 1; %>
    </tr>
    <% } %>
    <input type"submit" />
<% } %>
于 2009-06-16T10:09:28.853 回答