在asp.net MVC中获取下拉列表的选定值

时间:2010-05-08 09:48:53

标签: asp.net-mvc model-view-controller drop-down-menu

我如何获得下拉列表的选择值,这是我的代码工作正常。

    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>)%>

1 个答案:

答案 0 :(得分:1)

您在model.Peoples中使用的DropDownListFor属性必须是整数类型。它将绑定到您要提交此表单的控制器操作中的选定值:

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

备注:Peoples属性的语义更正确的名称为PersonId