Question

I know there are multiple threads on how to get the selected value of a DropDownList. However I can't find the right way to get this value from a partial view in my controller.

This is my partial view:

@model List<aptest.Models.answer>

@Html.DropDownList("dropdownlist", new SelectList(Model, "text", "text"))
<button type="submit">next</button>
Was it helpful?

Solution

In order to get dropdown value, wrap your select list in a form tag. Use models and DropDownListFor helper

Razor View

@model MyModel

@using (Html.BeginForm("MyController", "MyAction", FormMethod.Post)
{
   @Html.DropDownListFor(m => m.Gender, MyModel.GetGenderValues())
   <input type="submit" value="Send" />
}

Controller and other classes

public class MyController : Controller 
{
    [HttpPost]
    public ActionResult MyAction(MyModel model)
    {
        // Do something

        return View();
    }
}

public class MyModel
{
    public Gender Gender { get; set; }

    public static List<SelectListItem> GetGenderValues()
    {
        return new List<SelectListItem> 
        {
            new SelectListItem { Text = "Male", Value = "Male" };
            new SelectListItem { Text = "Female", Value = "Female" };
        };
    }
}

public enum Gender 
{
    Male, Female
}

And if you use partial view, simply pass your model in it:

@Html.Partial("MyPartialView", Model)

OTHER TIPS

ViewData["list"] = myList.ToList(); 

Razor

@Html.DropDownList("ddl", new SelectList((System.Collections.IEnumerable)ViewData["list"], "Id", "Name"))

Controller

public ActionResult ActionName(String ddl)
{

  // now ddl has your dropdownlist's selected value i.e Id

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top