2012-08-01 160 views
0

我從表tblemployee中選擇要將其綁定到下拉列表的數據時遇到問題。使用asp.net mvc 2.0將數據從數據庫綁定到dropdownlist

模式

public class UserModels 
{ 
    public string EmployeeName { get; set; } 
    public int EmployeeCode { get; set; } 
    public IEnumerable<SelectListItem> Employee { set; get; } 
} 

控制器

public ActionResult Education() { 

     var query = (from e in context.tblEmployee_Employee 
        select new 
        { 
         empID = e.Code, 
         EmpName = e.NameEng 
        } 
          ).ToList(); 

     var model = new UserModels(); 
     var _Emp = query; 
     foreach (var item in _Emp) 
     { 
      model.EmployeeCode = item.empID; 
      model.EmployeeName = item.EmpName; 
      model.Employee = new SelectList(_Emp, "EmpName", "EmpName"); 

     } 

     return View(model); 
    } 

查看

<%= Html.DropDownListFor(x => x.EmployeeName, Model.Employee, "select EmployeeName")%> 

而且我得到了錯誤消息「對象重沒有設置一個對象的實例「。任何人都知道請告訴我如何解決它。 謝謝,

回答

0

嘗試這樣的:

public ActionResult Education() 
{ 
    var model = new UserModels(); 
    model.Employee = context 
     .tblEmployee_Employee 
     .ToList() 
     .Select(e => new SelectListItem 
     { 
      Value = e.Code.ToString(), 
      Text = e.NameEng 
     }); 
    return View(model); 
} 

,並確保你的看法是強類型的UserModels視圖模型,然後:

<%= Html.DropDownListFor(
    x => x.EmployeeName, 
    Model.Employee, 
    "select EmployeeName" 
) %> 
+0

謝謝,但我還是得到了同樣的錯誤。 – Maly 2012-08-01 16:57:05

+0

你會在哪一行發生錯誤? – 2012-08-01 17:08:05

+0

我對視圖模型有錯誤「<%= Html.DropDownListFor(x => x.EmployeeName,Model.Employee,」select EmployeeName「)%>」。它顯示錯誤是「Object reference not set an instance of一個對象「 – Maly 2012-08-01 17:30:26

相關問題