您可以通过所选择的值作为第四选择列表的构造函数的参数:
var query = newdb.Incident.Select(c => new { c.ID, c.Name });
ViewBag.items = new SelectList(query.AsEnumerable(), "ID", "Name", "4");
,并在您的视图确保您使用的是不同的值作为第一个参数DropDownList的帮手,因为现在你正在使用"items"
这是不对的,因为第一个参数代表将使用的生成的下拉列表的名称b ACK在控制器中获取所选值:
@Html.DropDownList(
"selectedIncidentId",
(SelectList) ViewBag.items,
"--Select a Incident--"
)
另外我想使用的视图模型建议你和DropDownListFor助手的强类型版本:
public class IncidentsViewModel
{
public int? SelectedIncidentId { get; set; }
public IEnumerable<SelectListItem> Incidents { get; set; }
}
然后:
public ActionResult Foo()
{
var incidents = newdb.Incident.ToList().Select(c => new SelectListItem
{
Value = c.ID.ToString(),
Text = c.Name
});
var model = new IncidentsViewModel
{
SelectedIncidentId = 4, // preselect an incident with id = 4
Incidents = incidents
}
return View(model);
}
并在您的强类型视图中:
@model IncidentsViewModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(
x => x.SelectedIncidentId,
Model.Incidents,
"--Select a Incident--"
)
<button type="submit">OK</button>
}
请参阅我的教程[使用DropDownList框和jQuery] [1]和[我的博客Cascading DropDownList在ASP.Net MVC] [2] [1]:http://www.asp.net/mvc/tutorials/javascript/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc [2]:http://blogs.msdn.com/b/rickandy/archive /2012/01/09/cascasding-dropdownlist-in-asp-net-mvc.aspx – RickAndMSFT 2012-03-09 20:24:14