2009-06-16 142 views
0

MVC Html.CheckBox and form submit issue正确的提交形式与基于自动生成的控制

让我们看看下面的例子。查看:

<% 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) 

+0

Andrey,我发布了另一个解决方案。尝试一下。 – 2009-06-17 20:04:41

回答

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's ComputerZen.com - ASP.NET Wire Format for Model Binding to Arrays, Lists, Collections, Dictionaries

更新:

如果是的applicationID从数据库的关键是更好地使用AppList<App>作为行动参数。然后你的表单会看起来如下:

<% 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" /> 
<% } %> 
+0

这似乎是我需要的东西,但现在我没有成功。 1.我发现如果app.ApplicationId没有排序并且有漏洞。因为它是数据库键(例如1,2,5,11),applist参数作为空来到控制器。如果我采取一些迭代键,如<%i++;%>它的作品。 2.第二个问题是,即使未选中复选框,它也会形成(当然)所有对象。添加一些额外的领域模型来表明是否选择这样的记录似乎对我来说不是一个好主意。 – 2009-06-16 23:39:31