Metaphor
Metaphor

Reputation: 6415

Using Html.DropDownList helper with a ViewBag list

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.

Upvotes: 2

Views: 12132

Answers (2)

Jonathan Hallam
Jonathan Hallam

Reputation: 26

@{
   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"));

Upvotes: 1

John H
John H

Reputation: 14640

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.

Upvotes: 6

Related Questions