0

我从表 tblemployee 中选择的数据有问题,我想将其绑定到下拉列表。

模型

 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")%>

我收到错误消息“对象引用未设置对象的实例”。任何知道的人请告诉我如何解决它。谢谢,

4

1 回答 1

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"
) %>
于 2012-08-01T16:43:54.927 回答