您可以通過所選擇的值作爲第四選擇列表的構造函數的參數:
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