【问题标题】:The model item passed into the dictionary is of type 'System.Collections.Generic.List... in ASP.net MVC传入字典的模型项是 ASP.net MVC 中的“System.Collections.Generic.List...”类型
【发布时间】:2014-01-12 07:42:23
【问题描述】:

我在从 ASP.net MVC 实体框架中的两个表加入后检索数据,但在视图内部无法访问属性,当我运行代码时出现错误:传递到字典中的模型项的类型为“System.Collections” .Generic.List1[<>f__AnonymousType16..... 但是这本词典....System.Collections.Generic.IEnumerable`1。谢谢你的回答。。

我的代码是:

家庭控制器:

 dbEntities dbquery = new dbEntities();

        public ActionResult Index()
        {
            var id = 1;
            var query = (from x in dbquery.Emp_
                         join y in dbquery.Departments on x.Id equals y.emp_id
                         where x.Id == id
                         select new { x.Id, x.EmployeeName, x.Department, y.emp_id, y.Dept_Id, y.DeptName }).ToList(); 
            return View(query.ToList());

        }

在视图中:

@model IEnumerable

  @foreach (var item in Model)
  { 
   @item.... (Properties are inaccessible)
  }

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4


    【解决方案1】:

    razor 视图不支持使用匿名类型。

    您应该创建一个可以填充的模型。在模型中添加您需要的所有属性。

    代替

      select new { } 
    

    你会去的

      select new MyModel  { } 
    

    查询将返回一个

        List<MyModel>
    

    在这些变化之后。

    那么在您看来,您可以将模型更改为:

         @model IEnumerable<MyModel>
    

    【讨论】:

    • @user3026519 - 太好了。很高兴我能帮上忙。
    • 嗨,我也是这样做的,但还是有这个问题!我该怎么办?
    • @minaa.beigi 你认为你有什么类型(@model),你的控制器操作返回什么类型?
    • @scheien 在我看来使用IEnumerable&lt;MyModel&gt; 并且我的操作返回一个列表视图,但我找到了一种方法!从表中选择AsEnumerable() 所以我使用此代码var list = (from p in _dbContext.tbl_Tpaper.AsEnumerable() where p.Username == Name select new Teacherpapers { PaperName = p.PaperName, id=p.id }).ToList()
    猜你喜欢
    • 2014-01-02
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    相关资源
    最近更新 更多