的SelectList
構造(在其中您希望能夠通過所選擇的值id)的最後一個參數,因爲DropDownListFor助手使用您作爲第一個參數傳遞lambda表達式,並使用特定屬性的值將被忽略。
因此,這裏的醜陋的方式做到這一點:
型號:
public class MyModel
{
public int StatusID { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: obviously this comes from your DB,
// but I hate showing code on SO that people are
// not able to compile and play with because it has
// gazzilion of external dependencies
var statuses = new SelectList(
new[]
{
new { ID = 1, Name = "status 1" },
new { ID = 2, Name = "status 2" },
new { ID = 3, Name = "status 3" },
new { ID = 4, Name = "status 4" },
},
"ID",
"Name"
);
ViewBag.Statuses = statuses;
var model = new MyModel();
model.StatusID = 3; // preselect the element with ID=3 in the list
return View(model);
}
}
查看:
@model MyModel
...
@Html.DropDownListFor(model => model.StatusID, (SelectList)ViewBag.Statuses)
,這裏是正確的方法,用真實的視圖模型:
型號
public class MyModel
{
public int StatusID { get; set; }
public IEnumerable<SelectListItem> Statuses { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: obviously this comes from your DB,
// but I hate showing code on SO that people are
// not able to compile and play with because it has
// gazzilion of external dependencies
var statuses = new SelectList(
new[]
{
new { ID = 1, Name = "status 1" },
new { ID = 2, Name = "status 2" },
new { ID = 3, Name = "status 3" },
new { ID = 4, Name = "status 4" },
},
"ID",
"Name"
);
var model = new MyModel();
model.Statuses = statuses;
model.StatusID = 3; // preselect the element with ID=3 in the list
return View(model);
}
}
查看:
@model MyModel
...
@Html.DropDownListFor(model => model.StatusID, Model.Statuses)
請參閱下面的鏈接。 http://stackoverflow.com/questions/5188563/asp-net-mvc-drop-down-list-selection-partial-views-and-model-binding – 2012-04-06 04:42:17
alok_dida,我看了一下,它看起來很除了在構造SelectList時選擇的值使用整個對象與ID.ToString()像我在做的一樣。然而,我改變了我的代碼做同樣的事情,並沒有解決問題。兩者之間有一些差異,我錯過了可以解決我的問題嗎? – azorr 2012-04-06 04:48:55
我添加了一個如何完成的詳細示例。 – 2012-04-06 13:23:43