user8270367
user8270367

Reputation:

ASP.NET MVC Select Option Value of SelectList

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.

Upvotes: 0

Views: 4748

Answers (1)

Shyju
Shyju

Reputation: 218722

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

Upvotes: 2

Related Questions