2012-07-18 54 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

相關問題