Group DropDownList in Asp.Net MVC 4
In this
blog, I’m explaining about group dropdownlist in asp.net mvc 4 and how to
create it.
If you want
to learn about the dropdownlist first then you can see my below blogs:
Step 1
First
create a basic asp.net mvc 4 web application.
To create a
group dropdownlist in asp.net mvc 4, you need to download a package from nugget
gallery named DropDownList.Optgroup.MVC
To download
the above package in your project,
Go to Tools
> Nuget Package Manager > Package Manager Console like in the below
image:
If Nuget
Package Manager is not available in Tools menu, then there will be Library
Package Manager
Now download
and install the package DropDownList.Optgroup.MVC by typing:
Install-Package
DropDownList.Optgroup.MVC
And press
Enter like in the below image:
This will
install the package in your project and you are ready to create the group dropdownlist.
Step 2
Now add a
controller and named “HomeController” and write the below code in it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GroupDropDownListMvcApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
List<GroupedSelectListItem> list = new List<GroupedSelectListItem>();
list.Add(new GroupedSelectListItem { Text = "Cricket", Value
= "Cricket", GroupName = "Outdoor Games", GroupKey = "Outdoor Games" });
list.Add(new GroupedSelectListItem { Text = "Hockey", Value
= "Hockey", GroupName = "Outdoor Games", GroupKey = "Outdoor Games" });
list.Add(new GroupedSelectListItem { Text = "Football", Value
= "Football", GroupName = "Outdoor Games", GroupKey = "Outdoor Games" });
list.Add(new GroupedSelectListItem { Text = "Chess", Value
= "Chess", GroupName = "Indoor Games", GroupKey = "Indoor Games" });
list.Add(new GroupedSelectListItem { Text = "Playing Cards", Value = "Playing
Cards", GroupName = "Indoor Games", GroupKey = "Indoor Games" });
list.Add(new GroupedSelectListItem { Text = "Carrom", Value
= "Carrom", GroupName = "Indoor Games", GroupKey = "Indoor Games" });
return View(list);
}
}
}
Step 3
Now add
view named “Index” and write the below code in it:
@{
ViewBag.Title =
"Index";
}
<div>
@Html.DropDownGroupList("GamesList", Model as List<GroupedSelectListItem>, "Select Game", new { @style="padding:5px;"})
</div>
Output
Now run the
application:
No comments:
Post a Comment