2013-04-09 18 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