2009-06-16 140 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