asp.net-mvc 在 ASP.NEt MVC 3 中的 Html.BeginForm() 中传递 DropDownList 的 SelectedValue
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10187469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass SelectedValue of DropDownList in Html.BeginForm() in ASP.NEt MVC 3
提问by Saeid
This is my View Code:
这是我的查看代码:
@using(Html.BeginForm(new { SelectedId = /*SelectedValue of DropDown*/ })) {
<fieldset>
<dl>
<dt>
@Html.Label(Model.Category)
</dt>
<dd>
@Html.DropDownListFor(model => Model.Category, CategoryList)
</dd>
</dl>
</fieldset>
<input type="submit" value="Search" />
}
As code shown I need to pass the dropdownselected value to the action in BeginForm()Html helper. What is your suggestion?
如代码所示,我需要将dropdown选定的值传递给BeginForm()Html 助手中的操作。你的建议是什么?
回答by Darin Dimitrov
The selected value will be passed when the form is submitted because the dropdown list is represented by a <select>element. You just need to adapt your view model so that it has a property called SelectedIdfor example to which you will bind the dropdown:
提交表单时将传递选定的值,因为下拉列表由一个<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" />
}
This assumes the following view model:
这假设以下视图模型:
public class MyViewModel
{
[DisplayName("Select a category")]
public int SelectedId { get; set; }
public IEnumerable<SelectListItem> CategoryList { get; set; }
}
that will be handled by your controller:
将由您的控制器处理:
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);
}

