Reputation: 5008
my view:
@using (Html.BeginForm("Index", "Person"))
{
@Html.DropDownList("Departments",ViewData["Departments"] as SelectList)
<button type="submit">Select</button>
}
my DepartmentController:
public ActionResult Index()
{
ViewData["Departments"] = new SelectList(db.Departments, "ID", "Name");
return View();
}
my PersonController
public ActionResult Index(string id = null)
{
if (id != null)
{
//Return list of persons with department id
}
return View();
}
My problem: When I select a department from the DropDown and press the button, it redirects fine, but the id is not passed. What am I missing? I'm guessing it has to do with how i fill the DropDownList? Anyway, as always, thanks in advance
Upvotes: 0
Views: 550
Reputation: 18883
The problem in your case that mvc model binding is done with name attribute and @Html.DropDownList("Departments"...
will render html with dropdown having name 'Departments'
so either try my first answer or change @Html.DropDownList("Departments"...
as shown in my second answer.
Try This :
public ActionResult Index(string Departments) // <------ Use 'Departments' here instead of 'id'
{
.....
return View();
}
OR change dropdownlist
as :
@Html.DropDownList("id",ViewData["Departments"] as SelectList)
Upvotes: 1
Reputation: 8781
The name attribute of your dropdown is not "id" so the MVC model binder can not bind it. Add html attribute new {@Name ='id'} to your DropDown definition and it should work.
I also would suggest that your view receive a model - in this case model binding will be much easier, and you could use DropDownFor helper.
Using model also allows you to avoid using ViewData and ViewBag containers that are not recommended because they are not strongly typed so if by mistake you write ViewData["Departnents"] in your View you won't get a compilation error because of the typo, but clearly it won't work.
As an opposite you can define a model
public class Person
{
public SelectList Departments {get; set;}
public int SelectedDepatrmentId {get; set;}
//Other person properties come here
}
In your View the only thing you should do to make it work is:
@model path to your Person class
@Html.DropDownListFor(model => model.SelectedDepatrmentId, Model.Departments)
Upvotes: 4