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

19,929

Start by giving your select tag a valid 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);
}
Share:
19,929

Related videos on Youtube

James Santiago
Author by

James Santiago

Code and systems, systems and code

Updated on April 24, 2022

Comments

  • James Santiago
    James Santiago about 2 years

    I have a form posting to an action with MVC. I want to pull the selected drop down list item from the FormCollection in the action. How do I do it?

    My Html form:

    <% 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);
    }
    
  • James Santiago
    James Santiago almost 14 years
    Oh snap! Thanks, that did the trick. I tried both ways but I like how you used the action parameter.