下拉列表中的数据绑定

时间:2014-02-12 11:27:35

标签: c# asp.net-mvc razor

我正在练习MVC 4 Razor,我想在Dropdownlist中显示列表数据,我尝试了很多选项,但我无法填充数据,我正在使用WCF服务 我尝试使用List和IEnum我可以在控制器中获取数据,但是如何在下拉列表中显示数据。我在这里粘贴了我的代码

   public List<Employee> GetEmployeeList()
    {
        List<Employee> lstEmp = new List<Employee>();
        try
        {
            sqlConn = new SqlConnection(strConn);
            sqlConn.Open();
            query = "select ID,FirstName from Employee";
            sqlcmd = new SqlCommand(query, sqlConn);
            SqlDataReader dr = sqlcmd.ExecuteReader();                
            if (dr.HasRows)
            {
                Employee objHeader = new Employee();
                objHeader._ID = 0;
                objHeader._FirstName = "Select Employee";
                lstEmp.Add(objHeader);                    
                while(dr.Read())
                {
                    Employee objemp = new Employee();
                    objemp._ID = (int)dr["ID"];
                    objemp._FirstName = dr["FirstName"].ToString();
                    lstEmp.Add(objemp);
                }

            }
            else
            {
                Employee objNo =new Employee();
                objNo._ID = 0;
                objNo._FirstName = "No Records Found";
                lstEmp.Add(objNo);
            }
        }
        catch(Exception err)
        {

        }
        sqlcmd.Dispose();
        sqlConn.Close();
        return lstEmp;
    }

     public ViewResult Crud()
    {
        pxy.Open();
        emplist = pxy.GetEmployeeList().ToList();          
        IEnumerable<Employee> empEnum = emplist;            
        ViewData["lstEmp"] = new SelectList(empEnum);
        pxy.Close();            
        return View();   
    }
    @Html.DropDownList("Employee", ViewData["lstEmp"] as SelectList)

请帮帮我。

1 个答案:

答案 0 :(得分:0)

您可以使用以下语法:

 var dorpdownData=empEnum.Select(c=>new{c.key,c.value});
 viewdata["lstEmp"]=new selectlist(dropdowndata.asEnumerable(),"key","value");

然后在您看来:

  @Html.DropDownList("Employee", (selectlist)ViewData["lstEmp"])

希望这会有所帮助..