Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

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 null 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, List<SelectListItem> safely casts to SelectList

like image 871
Nkosi Avatar asked Oct 11 '16 14:10

Nkosi


1 Answers

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.

like image 179
Andrei Olariu Avatar answered Sep 22 '22 07:09

Andrei Olariu