Youcan make use of the MVC's
SelectListItem. Further reference can be found in :
Drop-down Lists and ASP.NET MVC[
^]
HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
EmployeeModel model = new EmployeeModel();
model.Positions = ReadData();
return View();
}
[NonAction]
private static List<SelectListItem> ReadData()
{
List<SelectListItem> Positions = new List<SelectListItem>();
string ConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(ConnString))
{
string query = "SELECT [DepartmentId] ,[Name] FROM[EmployeeTst].[dbo].[TblDepartment]";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = connection;
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Positions.Add(new SelectListItem
{
Text = reader["DepartmentId"].ToString(),
Value = reader["Name"].ToString()
});
}
}
connection.Close();
}
}
return Positions;
}
}
Index.cshtml
@model MVC.Models.EmployeeModel
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<table>
<tr>
<td>
@Html.DropDownListFor(p => p.EmployeeId, Model.Positions, "Please select")
</td>
</tr>
</table>
}