2

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
  • 6,157
  • 10
  • 54
  • 77
  • 1
    Why don't you construct the ViewBag on the server side. Then, you can simply refer to it in the dropdown. ViewBag.Casinos= new SelectList(Your IEnumerableList Here, "Values", "Values"); Then, your view will look something like this Html.DropDownList("Casinos", String.Empty) – Josiane Ferice Nov 14 '13 at 19:04

2 Answers2

6

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.

Community
  • 1
  • 1
John H
  • 14,422
  • 4
  • 41
  • 74
  • 1
    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. – Metaphor Nov 14 '13 at 19:31
  • 1
    @Metaphor Not a problem, I completely understand. Just wanted to be sure. – John H Nov 14 '13 at 19:32
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"));