提交表单时将传递所选值,因为下拉列表由<select>
元素表示。您只需要调整您的视图模型,使其具有一个名为SelectedId
例如您将绑定下拉列表的属性:
@using(Html.BeginForm() )
{
<fieldset>
<dl>
<dt>
@Html.LabelFor(x => x.SelectedId)
</dt>
<dd>
@Html.DropDownListFor(x => x.SelectedId, Model.CategoryList)
</dd>
</dl>
</fieldset>
<input type="submit" value="Search" />
}
这假设以下视图模型:
public class MyViewModel
{
[DisplayName("Select a category")]
public int SelectedId { get; set; }
public IEnumerable<SelectListItem> CategoryList { get; set; }
}
这将由您的控制器处理:
public ActionResult Index()
{
var model = new MyViewModel();
// TODO: this list probably comes from a repository or something
model.CategoryList = new[]
{
new SelectListItem { Value = "1", Text = "category 1" },
new SelectListItem { Value = "2", Text = "category 2" },
new SelectListItem { Value = "3", Text = "category 3" },
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// here you will get the selected category id in model.SelectedId
return Content("Thanks for selecting category id: " + model.SelectedId);
}