Asp.net mvc 在HttpPost视图中使用mvc3访问动态DropdownList
我为传递到视图中的字符串列表中的每个项目动态生成DropDownList,然后为一些标准选项生成DropDownList,DropDownList名称为字母drp+通过viewdata在视图中传递的字符串项目。我遇到的问题是,我不知道如何访问视图中HttpPost中的单个下拉列表,因为项目的名称和数量不同 以下是我的视图的获取代码:Asp.net mvc 在HttpPost视图中使用mvc3访问动态DropdownList,asp.net-mvc,model-view-controller,Asp.net Mvc,Model View Controller,我为传递到视图中的字符串列表中的每个项目动态生成DropDownList,然后为一些标准选项生成DropDownList,DropDownList名称为字母drp+通过viewdata在视图中传递的字符串项目。我遇到的问题是,我不知道如何访问视图中HttpPost中的单个下拉列表,因为项目的名称和数量不同 以下是我的视图的获取代码: public ActionResult ModMapping() { ViewData["mods"] = TempDat
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>
如果在视图中使用模型,这非常简单,因为MVC会自动将所有下拉列表映射回您的模型 如果您确实不想使用模型,请执行以下操作: 另一个选项是编写一个接受FormCollection的控制器函数,FormCollection只是POST中所有值的一个简单字典:
[HttpPost]
public ActionResult ModMapping(FormCollection formCollection)
{
// Load your modsList here.
foreach (String item in modsList)
{
var dropDownValue = formCollection["drp" + item];
}
}
您可能会简化工作,只需在FormCollection中循环查找以drp开头的项目,具体取决于您的页面和要求。您同意这一点,这对您自己来说非常困难。在你的视图中使用ViewBag和@DropDownFor会简单得多。这不起作用。我的[HttpPost]方法应该有什么作为输入参数?@StacieBartley-以什么方式不起作用?通过请求对象,您可以访问回发到服务器的所有数据。我还将用一个使用FormCollection的示例更新答案。
[HttpPost]
public ActionResult ModMapping(FormCollection formCollection)
{
// Load your modsList here.
foreach (String item in modsList)
{
var dropDownValue = formCollection["drp" + item];
}
}