Home ASP.NET MVC Select Option Value of SelectList

# ASP.NET MVC Select Option Value of SelectList

HighSepton
1#
HighSepton Published in 2017-11-10 21:12:59Z
 I am rendering a dropdown list. ViewBag.Categories = new SelectList(db.HelpCategories, "ID", "Name");  In my view I call it like this: Categories: @Html.DropDownList("Categories", (SelectList)ViewBag.Categories, "All")  For which I get select values like this.   I really need to set the value of "All" to 0. Can't figure out a way to do it. Found a tutorial that it's done with SelectListItem, but that doesn't fit my code. Any help is really appreciated, thank you.
Shyju
2#
 You can always build the SelectListItem list in your action method where you can add an item with the specific value and text explicitly, if you absolutely want that. var categoryList = new List { new SelectListItem { Value="0", Text = "All"} }; categoryList.AddRange(db.HelpCategories .Select(a => new SelectListItem { Value = a.Id.ToString(), Text = a.Name})); ViewBag.CategoryList = categoryList; return View();  Now in your view, you will use ViewBag.CategoryList to build the SELECT element @Html.DropDownList("Categories", ViewBag.CategoryList as IEnumerable)