简体   繁体   English

从MVC中的FormCollection获取选定的下拉列表值

[英]Get the selected drop down list value from a FormCollection in MVC

I have a form posting to an action with MVC. 我有一个表单发布到MVC的一个动作。 I want to pull the selected drop down list item from the FormCollection in the action. 我想从操作中的FormCollection中提取所选的下拉列表项。 How do I do it? 我该怎么做?

My Html form: 我的Html表格:

<% using (Html.BeginForm())
    {%>
    <select name="Content List">
    <% foreach (String name in (ViewData["names"] as IQueryable<String>)) { %>
          <option value="<%= name %>"><%= name%></option>
    <% } %>
    </select>
    <p><input type="submit" value="Save" /></p>
<% } %>

My Action: 我的行动:

[HttpPost]
public ActionResult Index(FormCollection collection)
{
    //how do I get the selected drop down list value?
    String name = collection.AllKeys.Single();
    return RedirectToAction("Details", name);
}

Start by giving your select tag a valid name . 首先为您的select标记提供有效name A valid name cannot contain spaces. 有效名称不能包含空格。

<select name="contentList">

and then fetch the selected value from the form parameters collection: 然后从表单参数集合中获取所选值:

var value = collection["contentList"];

Or even better: don't use any collections, use an action parameter which has the same name as the name of your select and leave the default model binder populate it: 甚至更好:不要使用任何集合,使用与您的选择名称同名的操作参数,并保留默认模型绑定器填充它:

[HttpPost]
public ActionResult Index(string contentList)
{
    // contentList will contain the selected value
    return RedirectToAction("Details", contentList);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM