Nkosi Nkosi - 13 days ago 7x
C# Question

How does List<SelectListItem> safely cast to SelectList in view

I was following a question where the OP had something like this

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();

And then in the view was able to do something like this

@Html.DropDownList("Status", ViewBag.Status as SelectList)

My expectation was that the result of the cast would be
and I stated as much. I was corrected that it should work and it was demonstrated via .net fiddle. To my surprise the dropdownlist was populated with the items.

My question: How is it that when done in the view,
safely casts to


This was a good question. I looked into the matter further and, indeed, if the selectList parameter is null, then the name parameter is used to look up a key in ViewData.

I'm basing this on http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/5cb74eb3b2f3#src/System.Web.Mvc/Html/SelectExtensions.cs

They even added a comment:

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);

And later on, the name is used:

private static IEnumerable<SelectListItem> GetSelectData(this HtmlHelper htmlHelper, string name)
    object o = null;
    if (htmlHelper.ViewData != null)
        o = htmlHelper.ViewData.Eval(name);

Good question @Nkosi. I had no idea this was possible.