2009-01-09 31 views
1

好吧,我是一個來自webforms背景的MVC新手,所以請原諒這裏的任何無知。這是我的場景。我有一張由應用程序和相關權限列表組成的表格。每個表格行由3條信息組成:複選框,描述行的一些文本以及允許用戶爲應用程序選擇適當權限的下拉列表。我想發佈這些數據,並且只處理被檢查過的表中的行(該行的id被嵌入爲複選框名稱)。從那裏,我想從DropDownList中獲取選定的值,並調用必要的代碼來更新數據庫。這裏是我查看網頁代碼:從ASP.NET MVC中的表解析表單發佈值?

  <%foreach (var app in newApps) 
       { %> 
       <tr> 
        <td><input type="checkbox" name="AddApps" value="<%=app.ApplicationId %>" /></td> 
        <td><%=Html.Encode(app.ApplicationName)%></td> 
        <td><%=Html.DropDownList("AppRole", new SelectList(app.Roles, "RoleId", "RoleDescription"))%></td> 
       </tr> 
       <%} %> 

我將如何檢索來自的FormCollection相應的值,當我到達的形式交控制器?過去,我只是通過調用Request.Form [「CheckBoxName」]並解析字符串來獲取複選框值來完成此操作。

或者我是否完全錯誤?

+0

看一看這個鏈接 http://stackoverflow.com/questions/5088450/simple-mvc3-question-how-to-retreive-form-values-from-httppost-dictionary-or – 2012-03-15 10:17:41

回答

2

你是半路權,以發表您的數據,該控制器可以讀取它必須是一個形式,所以裏面的信息:

 <% using(Html.BeginForm("Retrieve", "Home")) %>//Retrieve is the name of the action while Home is the name of the controller 
     <% { %> 
      <%foreach (var app in newApps)    { %> 
      <tr> 
       <td><%=Html.CheckBox(""+app.ApplicationId)%></td>  
      <td><%=Html.Encode(app.ApplicationName)%></td> 
       <td><%=Html.DropDownList("AppRole", new SelectList(app.Roles, "RoleId", "RoleDescription"))%></td> 
      </tr> 
     <%} %> 
     <input type"submit"/> 
    <% } %> 

和控制器上:

 public ActionResult Retrieve() 
    { 
     //since all variables are dynamically bound you must load your DB into strings in a for loop as so: 
     List<app>=newApps; 
     for(int i=0; i<app.Count;i++) 
     { 


     var checkobx=Request.Form[""+app[i].ApplicationId]; 
     // the reason you check for false because the Html checkbox helper does some kind of freaky thing for value true: it makes the string read "true, false" 
      if(checkbox!="false") 
      { 
      //etc...almost same for other parameters you want that are in thr form 
      } 

     } 
    //of course return your view 
    return View("Index");//this vaires by the name of your view ex: if Index.aspx 
    } 

這網站提供了更多關於如何處理dropdownlist助手的詳細信息:

http://quickstarts.asp.net/previews/mvc/mvc_HowToRenderFormUsingHtmlHelpers.htm

1

Request.Form仍然可以工作,除了您的複選框都具有相同的名稱。

所以一種方法是給複選框不同的名稱,例如「AddApps-app.id」,並使用Request.Form。

但是,更優雅和可測試的方式是使用列表綁定。

在這個模型中,你給你的表單元素一個特定的結構化名稱,默認的模型聯編程序將把每個表單元素集合包含到控制器中的類型化記錄列表中。 This is fully explained in this blog post

這裏的優點是您的控制器僅處理應用程序類型的實例,因此對視圖的構建方式沒有隱式依賴性。因此,單元測試非常容易。