Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the selected value of a DropDownList in MVC

Tags:

c#

asp.net-mvc

How can I get the selected value from the DropDown in MVC? I want to assign it to a variable.

This is my controller action:

public ActionResult Drop()
{
    List<SelectListItem> items = new List<SelectListItem>();
    items.Add(new SelectListItem { Text = "Action", Value = "0" });
    items.Add(new SelectListItem { Text = "Drama", Value = "1" });
    items.Add(new SelectListItem { Text = "Comedy", Value = "2" });
    items.Add(new SelectListItem { Text = "Science Fiction", Value = "3" });
    items.Add(new SelectListItem { Text = "Horror", Value = "4" });
    items.Add(new SelectListItem { Text = "Art", Value = "5"  });
    ViewData["Options"] = items;
}

This is my view:

@Html.DropDownList("Options", ViewData["Options"] as SelectList, "--Select Item--")
like image 253
being fab Avatar asked Aug 21 '12 07:08

being fab


2 Answers

View

@using (Html.BeginForm())
{ 
    <h2>Drop</h2>
    @Html.DropDownList("Options", ViewData["Options"] as SelectList, "--Select Item--")

    <input type="submit" name="submit" value="Submit" />
}

Controller Add a new action

[HttpPost]
public ActionResult Drop(FormCollection form)
{
    var optionsValue = form["Options"];
    //TODO:
    return RedirectToAction("Drop");
}
like image 97
Charlie Avatar answered Nov 15 '22 23:11

Charlie


Also, consider that if you are not using FormCollection in your post, you could easily use the following, this is very helpful especially if you are using partial views inside the main one.

[HttpPost]
public ActionResult Drop(SelectListItem item)
{

    var selectedValue = Request.Form["ID_OF_THE_DROPDOWNLIST"];
    //TODO......
    return RedirectToAction("Drop");
}
like image 28
Muhammad Soliman Avatar answered Nov 15 '22 22:11

Muhammad Soliman