0
votes

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.

<select id="Categories" name="Categories">
   <option value="">All</option>
   <option value="1">Dėl Krepšelių</option>
</select>

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.

1
Why would you want to set it to 0? And if you do want it then you must generate an IEnumerable<SelectListItem> that incluse one with Value="0" and Text="All" (and delete the 3rd parameter in your DropDownList() method) - user3559349

1 Answers

1
votes

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<SelectListItem>
{
    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<SelectListItem>)