I want to bind Data from DB to DropDownList ,i had tried the following method but the data is not binded to the dropdown can any one tell where am i doing wrong
this is my controller
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult AddNew()
{
ViewBag.RoleName = new SelectList(GetRoles(), "RoleID", "RoleName");
return View();
}
public List<SelectListItem> GetRoles()
{
var roles = new List<SelectListItem>();
SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True");
SqlCommand Cmd = new SqlCommand("Select GroupId,EmplopyeeRole from EmployeeGroup", conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(Cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i <= ds.Tables[0].Rows.Count-1; i++)
{
var model = new ResourceModel();
model.RoleId = Convert.ToInt16(ds.Tables[0].Rows[i]["GroupId"]);
model.RoleName = ds.Tables[0].Rows[i]["EmplopyeeRole"].ToString();
}
conn.Close();
return roles;
}
this is my model
public class ResourceModel
{
public static List<ResourceModel> GetList { get; set; }
public Int16 EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string EmployeeEmailId { get; set;}
public string GroupName { get; set; }
public string EmployeePassword { get; set; }
public static List<SelectListItem> GetRoles { get; set; }
public int RoleId { get; set; }
public string RoleName { get; set; }
}
this is my aspxPage
<%:Html.DropDownList("RoleName")%>
when i put a breakpoint and see that i have the data in GetRoles Method..can any one tell me where am i doing wrong
I guess the problem is you have a property in the model with the name
RoleNameand also you have it in theViewBag.So when you use
<%:Html.DropDownList("RoleName")%>there is a kind of confusion.I would suggest change
ViewBag.RoleNameinto something likeViewBag.Rolesand then try,<%:Html.DropDownList("Roles")%>