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" })
CodePudding user response:
actually give a select list instead of a string list from the controller.
ViewBag.CategoryList = YourList.Select(r => new SelectListItem()
{
Value = r.SomeID,
Text = r.Category
})
@Html.DropDownListFor(model => model.Category, new SelectList(ViewBag.CategoryList, "Value", "Text"), "Select Category", htmlAttributes: new {@class = "form-control"})
CodePudding user response:
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" })
