List <SelectListItem>如何在视图中安全地转换为SelectList

Nko*_*osi 12 c# asp.net asp.net-mvc

我正在关注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();
}
Run Code Online (Sandbox Code Playgroud)

然后在视图中能够做到这样的事情

@Html.DropDownList("Status", ViewBag.Status as SelectList)
Run Code Online (Sandbox Code Playgroud)

我的期望是演员的结果将是null和我说的一样多.我纠正了它应该工作,并通过.net小提琴演示.令我惊讶的是,下拉列表中填充了这些项目.

我的问题:如何在视图中完成,List<SelectListItem>安全地转换为SelectList

小智 10

这是一个很好的问题.我进一步研究了这个问题,实际上,如果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);
       ...
Run Code Online (Sandbox Code Playgroud)

以后,name使用:

private static IEnumerable<SelectListItem> GetSelectData(this HtmlHelper htmlHelper, string name)
{
    object o = null;
    if (htmlHelper.ViewData != null)
    {
        o = htmlHelper.ViewData.Eval(name);
    }
    ...
Run Code Online (Sandbox Code Playgroud)

好问题@Nkosi.我不知道这是可能的.