2

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>
Andrei
  • 42,814
  • 35
  • 154
  • 218
JaperTIA
  • 129
  • 1
  • 2
  • 13

2 Answers2

10

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)
Andrei
  • 42,814
  • 35
  • 154
  • 218
  • he wants to get value from partial view not normal view!! – Neel Mar 28 '14 at 07:12
  • 1
    @Neel it doesn't matters. – Andrei Mar 28 '14 at 07:13
  • what do u mean by doesn't matter? – Neel Mar 28 '14 at 07:14
  • 1
    @Neel After the partial view has rendered it doesn't matter whether the dropdown was inside a partial view.So long it is rendered under a form tag its value is posted to the server and can be accessed in FormCollection or Request object. – Ashutosh Mar 28 '14 at 07:17
  • Thank you very much, it's working! damn i have no idea how i could struggle so badly.. – JaperTIA Mar 28 '14 at 07:21
  • @AndreiMikhalevich This helps me bind to the list and POST back the value, but it does not choose the correct selected value. How do you specify the selected value? – L_7337 May 15 '14 at 14:28
  • Ok, I found it. I just added the selected value to the SelectList. `@Html.DropDownList("dropdownlist", new SelectList(Model, "text", "text", Model.SelectedValue))` – L_7337 May 15 '14 at 14:59
  • @Andrei M -Thanks a lot!, for this i can used like this, we can avoid list method. – charulatha krishnamoorthy Oct 06 '16 at 06:45
2
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

}
rb4bhushan
  • 115
  • 2
  • 11