2012-07-18 135 views
0

我要绑定的数据从DB为DropDownList,我曾试过以下方法,但数据不会绑定到下拉任何一个可以告诉我在哪里做错了如何将数据绑定到MVC3中的DropDownList?

这是我的控制器

  [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; 
    } 

这是我的模型

   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; }  

} 

这是我aspxPage

<%:Html.DropDownList("RoleName")%> 

当我把一个断点,看到我在GetRoles Method..can数据的任何一个告诉我,我做错了什么

回答

0

我想问题是你在模型中有一个属性名称RoleName,你也有它在ViewBag

所以当你使用<%:Html.DropDownList("RoleName")%>时会有一种混淆。

我建议改变ViewBag.RoleName成类似ViewBag.Roles,然后尝试,

<%:Html.DropDownList("Roles")%>

+0

@ Mark..i试过这个,但仍然是一样的 – SoftwareNerd 2012-07-18 10:34:23

0
在for循环

,使用roles.add(new SelectList{.Value=i, .Text=i});领域,而不是i

在视图页面使用<%: Html.DropDownList("RoleName", New SelectList(youClass.GetRoles, "Value", "Text"))%>和youClass导入页面。

linq和foreach也很好用〜并且开发成为一种合适的扩展方法。

+0

抱歉,我天玑得到你......你能告诉我在哪里,我要补充一点,声明 – SoftwareNerd 2012-07-18 10:16:18

相关问题