Home ASP.NET MVC Select Option Value of SelectList
Reply: 1

ASP.NET MVC Select Option Value of SelectList

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.

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

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 Reply to 2017-11-10 21:17:54Z

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"}

                        .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>)
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.323682 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO