Hi sidu,
Html.DropDownList has 8 overload method and all of them take IEnumerable<SelectListItem> as the parameter that will hold your values.
You cannot direcly use your own class for that.
So for binding from database refer below code.
Database
For this example I have used of NorthWind database that you can download using the link given below.
Download Northwind Database
Model
public class Employee
{
public int empid { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public bool sex { get; set; }
public DateTime dateofbirth { get; set; }
public string city { get; set; }
public string addresss { get; set; }
public List<SelectListItem> countries { get; set; }
}
Controller
public ActionResult Index()
{
Employee emp = new Employee();
emp.countries = PopulateCountries();
return View(emp);
}
private static List<SelectListItem> PopulateCountries()
{
List<SelectListItem> countries = new List<SelectListItem>();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "SELECT DISTINCT Country FROM Employees";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
countries.Add(new SelectListItem
{
Text = sdr["Country"].ToString(),
Value = sdr["Country"].ToString()
});
}
}
con.Close();
}
}
return countries;
}
View
@model _DropDownList_DataBase_Model.Models.Employee
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div class="col-xs-2">
Choice the language
@Html.DropDownList("sellan", Model.countries, "select language")
</div>
</body>
</html>
Screenshot
