あなたは第四として選択された値を渡すことができことを願ってSelectListのコンストラクタの引数:
var query = newdb.Incident.Select(c => new { c.ID, c.Name });
ViewBag.items = new SelectList(query.AsEnumerable(), "ID", "Name", "4");
とまたあなたのビューで、今あなたが間違っている"items"
を使用しているため、最初の引数が表すので、あなたは、DropDownListのヘルパーの最初の引数として別の値を使用していることを確認してください生成されるドロップダウンリストの名前b
@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);
}
選択された値を取得するために、コントローラにackを
、強く型付きのビュー:
@model IncidentsViewModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(
x => x.SelectedIncidentId,
Model.Incidents,
"--Select a Incident--"
)
<button type="submit">OK</button>
}
私のチュートリアル[DropDownList BoxとjQueryを使って作業する] [1] [ASP.Net MVCで私のブログCascading DropDownList] [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