skip to Main Content

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


  1. 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"}) 
    
    Login or Signup to reply.
  2. 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" })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search