2013-04-09 15 views
1

我爲字符串列表中的每個項目動態生成DropDownList我進入我的視圖,然後爲一些標準選項生成一個下拉列表,其中的下拉列表名稱是字母「drp」+通過viewdata在視圖中傳遞的字符串項目。我遇到的問題是,我無法弄清楚如何訪問視圖中HttpPost中的單獨下拉列表,因爲名稱和項目數量不盡相同。在HttpPost中使用MVC 3訪問動態DropdownList查看

這是我爲我的觀統領代碼:

public ActionResult ModMapping() 
     { 

      ViewData["mods"] = TempData["mods"]; 
      return View(); 
     } 

這裏是我的視圖生成:

<% using (Html.BeginForm()) { %> 

<h2>Modifier Needing Mapping</h2> 
<p>Please Choose for each modifier listed below what type of fee it is. There is an ingore option if it is not a gloabl fee modifier, professional fee modifier, or technical fee modifier.</p> 
<table> 
    <tr> 
     <th>Modifier</th> 
     <th>Mapping Options</th> 
    </tr> 
     <% int i; 
      i=0; 
      var modsList = ViewData["mods"] as List<String>;%> 

     <% foreach (String item in modsList) { %> 
      <% i++; %> 
      <tr> 
       <td> 
        <%: Html.Label("lbl" + item, item) %> 
       </td> 
       <td> 
        <%: Html.DropDownList("drp" + item, new SelectList(
        new List<Object>{ 
         new { value = "NotSelected" , text = "<-- Select Modifier Type -->"}, 
         new { value = "Global" , text = "Global Fee" }, 
         new { value = "Professional" , text = "Professional Fee"}, 
         new { value = "Technical", text = "Technical Fee"}, 
         new { value = "Ingore", text="Ingore This Modifier"} 
        }, 
        "value", 
        "text", 
        "NotSelected")) %> 
       </td> 
      </tr> 
     <% } %> 
</table> 
<input type="submit" value="Done" /> 
<% } %></code> 

回答

0

這是非常簡單,如果你使用一個模型視圖,如MVC將映射所有的下拉列表會自動返回到您的模型。

如果你真的不想使用模型,you can access the values in the form like this

// Load your modsList here. 
foreach (String item in modsList) 
{ 
    var dropDownValue = Request["drp" + item]; 
} 

另一種選擇是寫一個接受的FormCollection,這是在所有值只是一個簡單的字典中的控制器功能POST:

[HttpPost] 
public ActionResult ModMapping(FormCollection formCollection) 
{ 
    // Load your modsList here. 
    foreach (String item in modsList) 
    { 
     var dropDownValue = formCollection["drp" + item]; 
    } 
} 

你也許可以簡化通過的FormCollection的事情,只是循環尋找與「DRP」啓動項,這取決於你的頁面,並要求樣子。

+0

同意你讓自己變得非常困難。在視圖中使用ViewBag和@DropDownFor()會更容易。 – 2013-04-09 18:44:54

+0

這不起作用。我的[HttpPost]方法應該具有什麼作爲輸入參數? – 2013-04-12 13:58:36

+0

@StacieBartley - 不工作,以什麼方式?通過Request對象,您可以訪問所有發回服務器的數據。我也會用一個使用FormCollection的例子來更新答案。 – 2013-04-12 15:41:58