Please refer this code to bind the DropDownList in MVC.
View
Index.aspx
This is my first MVC application
<br />
List of Employees name
<%: @Html.DropDownList("ddlEmployees", (IEnumerable<SelectListItem>)ViewData["Employees"])%>
Namespaces
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
Controller
public class Default1Controller : Controller
{
public ActionResult Index()
{
ViewData["Employees"] = GetEmployees();
return View();
}
public List<SelectListItem> lst = new List<SelectListItem>();
public IEnumerable<SelectListItem> GetEmployees()
{
string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT EmployeeId, FirstName FROM Employees", con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
da.Fill(ds);
lst.Add(new SelectListItem() { Text = "--Select--", Value = "" });
foreach (DataRow dr in ds.Tables[0].Rows)
{
lst.Add(new SelectListItem() { Text = dr["FirstName"].ToString(), Value = dr["EmployeeId"].ToString() });
}
}
}
}
return lst;
}
}
Keep you View inside shared folder of View.
Screenshot