Using Html.DropDownList helper with a ViewBag list

11,962

Solution 1

@{
   IEnumerable<MyItemType> CDrop = ViewBag.Cat;


        List<SelectListItem> selectList = new List<SelectListItem>();
        foreach (var c in CDrop)
        {
            SelectListItem i = new SelectListItem();
            i.Text = c.Decsription.ToString();
            i.Value = c.TypeID.ToString();
            selectList.Add(i);
        }

}

}

    then some where in your view. 

    @Html.DropDownList("name", new SelectList(selectList, "Value","Text"));

Solution 2

It's not rendering because it's all inside a razor code block (i.e. @{ ... }). Try this:

@{
    List<SelectListItem> selectList = new List<SelectListItem>();
    foreach(Item c in ViewBag.Items)
    {
        SelectListItem i = new SelectListItem();
        i.Text = c.Name.ToString();
        i.Value = c.SiteID.ToString();
        selectList.Add(new SelectListItem());
    }
}

@using (Html.BeginForm())
{
    @Html.DropDownList("Casinos", new SelectList(selectList,"Value","Text"));
}

Here's a quick reference for razor syntax. Also, although you've mentioned this is throw-away code, I'll mention using view[1] models[2] anyway, just to be sure you're aware of them. I can provide a simple example, if you need one.

Share:
11,962
Metaphor
Author by

Metaphor

Updated on June 05, 2022

Comments

  • Metaphor
    Metaphor almost 2 years

    This is the code:

    @using SSA.Models;
    
    <h2>@ViewBag.Title.ToString()</h2>
    
    @{
        using(Html.BeginForm()){
            List<SelectListItem> selectList = new List<SelectListItem>();
            foreach(Item c in ViewBag.Items)
            {
                SelectListItem i = new SelectListItem();
                i.Text = c.Name.ToString();
                i.Value = c.SiteID.ToString();
                selectList.Add(new SelectListItem());
            }
            Html.DropDownList("Casinos", new SelectList(selectList,"Value","Text"));
        }
    }
    

    The list, selectList, on breakpoint shows it has 108 values. What renders is an empty form. No run time errors.

    Note: I know using the ViewBag for this is not the best method. This is throw-away code and I'd just like to understand why it is not rendering the dropdown.

  • Metaphor
    Metaphor over 10 years
    Thanks for the answer and for pointing out the benefits of a ViewModel. I'm aware of the value and benefits, just don't want the added complexity for this exercise.
  • John H
    John H over 10 years
    @Metaphor Not a problem, I completely understand. Just wanted to be sure.