我正在关注OP有这样的问题
[HttpGet]
public ActionResult Index() {
var options = new List<SelectListItem>();
options.Add(new SelectListItem { Text = "Text1", Value = "1" });
options.Add(new SelectListItem { Text = "Text2", Value = "2" });
options.Add(new SelectListItem { Text = "Text3", Value = "3" });
ViewBag.Status = options;
return View();
}
然后在视图中能够做到这样的事情
@Html.DropDownList("Status", ViewBag.Status as SelectList)
我的期望是演员阵容的结果 null
我也说了很多。我被纠正它应该工作,并通过.net小提琴演示。令我惊讶的是,下拉列表中填充了这些项目。
我的问题:在视图中完成后如何, List<SelectListItem>
安全地施展到 SelectList
这是一个很好的问题。我进一步研究了这个问题,的确如果 selectList
参数为null,然后是 name
参数用于查找键 ViewData
。
我是基于这个 http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/5cb74eb3b2f3#src/System.Web.Mvc/Html/SelectExtensions.cs
他们甚至添加了评论:
private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, ModelMetadata metadata, string optionLabel, string name, IEnumerable<SelectListItem> selectList, bool allowMultiple, IDictionary<string, object> htmlAttributes)
{
...
// If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
selectList = htmlHelper.GetSelectData(name);
...
后来, name
用来:
private static IEnumerable<SelectListItem> GetSelectData(this HtmlHelper htmlHelper, string name)
{
object o = null;
if (htmlHelper.ViewData != null)
{
o = htmlHelper.ViewData.Eval(name);
}
...
好问题@Nkosi。我不知道这是可能的。