2
votes

I am retrieving data after joining from two tables in ASP.net MVC Entity framework but the properties are unaccessible inside view and when i run the code it give error : The model item passed into the dictionary is of type 'System.Collections.Generic.List1[<>f__AnonymousType16..... but this dictionary....System.Collections.Generic.IEnumerable`1. Thanks for your answers..

My Code is:

HomeController:

 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());

        }

In View:

@model IEnumerable

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

1 Answers

7
votes

The use of anonymous types are not supported by razor views.

You should create a model you could populate. Add all the properties you need in the model.

Instead of

  select new { } 

you would go

  select new MyModel  { } 

The query would return a

    List<MyModel>

after these changes.

Then in your view you would change the model to:

     @model IEnumerable<MyModel>