【问题标题】:The model item passed into the dictionary is of type List, but this dictionary requires a model item of type IEnumerable传入字典的模型项是 List 类型,但是这个字典需要一个 IEnumerable 类型的模型项
【发布时间】:2016-01-21 15:20:19
【问题描述】:

我在下面遇到一个异常:

传入字典的模型项的类型为“System.Collections.Generic.List1[DropDownList.Models.Department]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[DropDownList.Models.Employee]”。

这是我的模型, Employee.cs:

public class Employee
{
    public int EmployeeId { get; set; }  
    public string EmployeeName { get; set; }
    public int DepartmentId { get; set; }

    public virtual Department Department { get; set; }
}

部门.cs:

public class Department
{
    public int DepartmentId { get; set; }
    public string DeptCode { get; set; }
    public string DepartmentName { get; set;}
    public string Syscode { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }
}

还有我的EmployeesController的索引动作,异常产生的地方:

public ActionResult Index()
{
var employees =
            from dept in db.Departments
            select new
            {
                dept,
                depts = from emp in dept.Employees
                        where dept.Syscode == "isols123"
                        select dept
            };
        var employs = employees
            .AsEnumerable()
           .Select(m => m.dept);
        return View(employs.ToList());
}

这是我的索引视图:

@model IEnumerable<DropDownList.Models.Employee>
.
.
@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Department.DepartmentName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.EmployeeName)
    </td>
</tr>
}

出了什么问题,我不知道,我严重卡在这个问题上 :(,任何人都请带我离开这里,在此先感谢..

【问题讨论】:

    标签: asp.net-mvc linq razor collections


    【解决方案1】:

    本质上,代码:

    public ActionResult Index()
    {
    var employees =
                from dept in db.Departments // This makes dept of type Department
                select new
                {
                    dept,
                    depts = from emp in dept.Employees
                            where dept.Syscode == "isols123"
                            select dept
                };
            var employs = employees
                .AsEnumerable()
               .Select(m => m.dept); // Selects Department
            return View(employs.ToList());
    }
    

    返回Departments 的列表(即使变量被称为employs)并且您的视图期望它是Employees 的列表。

    这两者都应该匹配才能正常工作。

    假设 linq 查询是正确的,这将使它在视图上期望一个部门列表:

    @model List<DropDownList.Models.Department>
    

    【讨论】:

    • 先生,实际上,我想在员工表单上创建一个部门下拉列表,所以如果这是问题,我该如何解决,我应该进行哪些更改?
    • 哦,我的错,我正在选择部门列表,而我应该选择员工列表,谢谢您的时间,先生..
    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2017-03-15
    • 2015-07-05
    相关资源
    最近更新 更多