Xulfee
Xulfee

Reputation: 986

Get selected value of dropdownlist in asp.net MVC

how can i get select value of dropdownlist and here is my code which is working fine.

    var list = new[] {   
    new Person { Id = 1, Name = "Name1" }, 
    new Person { Id = 2, Name = "Name2" }, 
    new Person { Id = 3, Name = "Name3" } 
};

var selectList = new SelectList(list, "Id", "Name", 2);
ViewData["People"] = selectList;

<%= Html.DropDownListFor(model => model.Peoples, ViewData["People"] as IEnumerable<SelectListItem>)%>

Upvotes: 0

Views: 3534

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

The model.Peoples property which you are using in the DropDownListFor must be of type integer. It will be bound to the selected value in the controller action to which you are submitting this form:

[HttpPost]
public ActionResult Index(YourModelType model)
{
    int selectedPersonId = model.Peoples;
    // TODO: do something with the id
    return View();
}

Remark: a more semantically correct name for the Peoples property would be PersonId.

Upvotes: 1

Related Questions