Getting System.Web.Mvc.SelectListItem as options of DropDownList

Viewed 247

I have a ViewBag.CategoryList which contains ViewBag.CategoryList = new SelectList(Category.GetCategories());

My View:

@Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DropDownListFor(model => model.Category, new SelectList(ViewBag.CategoryList), "Select Category", htmlAttributes: new {@class = "form-control"})

What I'm getting is <option>System.Web.Mvc.SelectListItem</option> instead of my strings. Debugger shows that the ViewBag does have a list of strings.

Edit: Fixed it by replacing the view with:

@Html.DropDownListFor(model => model.Category, (IEnumerable)(ViewBag.CategoryList), "Select Category", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Category, "", new { @class = "text-danger" })
2 Answers

actually give a select list instead of a string list from the controller.

ViewBag.CategoryList = Category.GetCategories().Select(r => new SelectListItem()
            {
                Value = r,
                Text = r
            })
@Html.DropDownListFor(model => model.Category, new SelectList(ViewBag.CategoryList, "Value", "Text"), "Select Category", htmlAttributes: new {@class = "form-control"}) 

try this

var list=Category.GetCategories();
ViewBag.CategoryList = list.Select(i => new SelectListItem
            {
                Value = i.Id.ToString(),
                Text = i.Name
            })

and view

@Html.DropDownListFor(model => model.Category, @ViewBag.CategoryList,"Select Category", htmlAttributes: new { @class = "form-control" })
Related