Written By:- Isha Malhotra
It is little bit tricky to create dropdown list in MVC using HTML Helper class. As we know that in general dropdown list we show data in Text and Value format.
Similarly here we have to create a class which contains the property for Text and Value.
As in HTML we use Form method in which we assign action, method etc here we use BeginForm to implement this task.
In this example I am creating dropdown list for countries. In which I am taking CID as a value field and CName as a Text Field.
Create controller name home and method index and create view for index method.
To add properties, add class and give it name country and declare two properties CID and CName.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication7
{
public class country
{
public int CID { get; set; }
public string CName { get; set; }
}
}
Now go to your index view and create a list of type country and add Items in this list.
@{
Layout = null;
List<MvcApplication7.country> lst_country = new List<MvcApplication7.country>()
{
new MvcApplication7.country{CID=1, CName="India"},
new MvcApplication7.country{CID=2, CName="USA"},
};
}
Now create dropdownlist using HTML Helper class.
@Html.DropDownList("drp_country", new SelectList(lst_country, "CID", "CName"))
In this DropDownList drp_country is id and Name for this control. We added SelectList in which we pass data source which is List and the name of ValueField and TextField.
@{
Layout = null;
List<MvcApplication7.country> lst_country = new List<MvcApplication7.country>()
{
new MvcApplication7.country{CID=1, CName="India"},
new MvcApplication7.country{CID=2, CName="USA"},
};
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@Html.DropDownList("drp_country", new SelectList(lst_country, "CID", "CName"))
</body>
</html>
The output of this code is as follows:-