How to create Dropdown list using Option group in MVC Razor?


How to create Dropdown list using Option group in MVC Razor syntax in View, like below iimage

option-group-in-mvc-razor.png

Any code or tutorial link? Thanks


Asked by:- jaiprakash
0
: 7182 At:- 4/6/2018 12:44:50 PM
Razor ASP.NET MVC C# mvc selectlistitem group







1 Answers
profileImage Answered by:- pika

First, you need to create a List or get of items from the database, here in this example we will show the below data list item

public static List<Car> GetCars()
    {
        return new List<Car>{
            new Car{Id=1, Name="Volvo", Category="Swedish Cars"},
            new Car{Id=2, Name="Mercedes-Benz", Category="German Cars"},
            new Car{Id=3, Name="Saab", Category="Swedish Cars"},
            new Car{Id=4, Name="Audi", Category="German Cars"},
            new Car{Id=5, Name="Audi", Category="German Cars"},

        };
    }

Car class C# Code

  public class Car
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
}

In your Controller, you can create SelectListItem using the above Cars data as

public ActionResult Index()
    {
       //Here Category is served as OptionGroup for dropdown list
        ViewBag.OptGroupCarList= new SelectList(Car.GetCars(), "Id", "Name","Category",1);
        return View();
    }

SelectList have 3 more overloaded constructors which take the grouping field name as one of the parameters. Here is a snapshot of the constructors supported by SelectList:

optgroup-in-asp-net-mvc-razor-csharp-min.png

In the above C# code, Id maps to data value field, Name maps to data text field and Category maps to data group field, and selected item = 1

In the View, You can use the ViewBag.OptGroupCarList as

        <h3>HTML OptGroup Razor Demo</h3>
        @Html.DropDownList("OptGroupCarList")

That's it you are done.

2
At:- 4/7/2018 6:35:33 PM
Great answer, OptGroup works for me in Razor now, thanks for your help 0
By : jaiprakash - at :- 4/8/2018 7:03:28 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use