您可以使用Html.DropDown助手。此帮助程序通过显示的选项获取IEnumerable。 在您的控制器中,您可以在ViewBag中发送下拉列表的值或使用View Model。您的视图模型的这一特性必须与SelectListItem(S)的列表,包括您的两个选项是和否,然后用你的过滤器的值来选择这样的正确的选择:
ViewBag.Status = new List<SelectListItem>(){
new SelectListItem
{
Value = "Yes",
Text = "Yes",
Selected = yourFilter.FilterStatus //If your status is Yes this will be true
//otherwise false.
},
new SelectListItem
{
Value = "No",
Text = "No",
Selected = yourFilter.FilterStatus //If your status is No this will be true
//otherwise false.
}
};
然后在您的视图您可以打印使用HTML帮助您的下拉列表:
@Html.DropDownList("Status", "--Select--")
使用ViewBag讲究的是属性的名称有名字的助手匹配,这将是相同的名称,该表单将寄在提交表单时回到控制器。
如果您使用的视图模型版本,那我建议你测试的目的,你必须创建一个视图模型,并指定下拉值是财产,是这样的:
//Don't create this class on the controller! This is only as an example.
public class FilterViewModel {
public bool Status {get; set;}
public IEnumerable<SelectListItem> statusDropDown {get; set;}
}
var myViewModel = new FilterViewModel();
myViewModel.statusDropDown = new List<SelectListItem>(){
new SelectListItem
{
Value = "Yes",
Text = "Yes",
Selected = yourFilter.FilterStatus
},
new SelectListItem
{
Value = "No",
Text = "No",
Selected = yourFilter.FilterStatus
}
};
return View(myViewModel);
你可以使用您的视图中的以下帮助程序:
@model Controllers.YourController.FilterViewModel
@Html.DropDownListFor(model => model.Status, Model.statusDropDown, "--Select--")
为什么不使用'@ Html.DropdownFor()'使其正确绑定? –
另外我在我的控制器中使用FormCollection。我想我不能从那里下拉数据。 (而且我也是mvc的新手)。 –
编辑你的问题,并把完整的代码,所以我们可以了解情况,即''Controller'类与'Action'方法代码(MVC部分),因为IMO'FormCollection'只用于其http' POST'及其在'Action'方法中使用 –