Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass linq query to view

Tags:

asp.net-mvc

I made a linq query which i want to pass to the view but it's giving me this error

The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery`1[<>f__AnonymousType4`2[System.String,System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1

My ViewModel

  public class ManageScoreViewModel
     {
         public string fullName { get; set; }
         public string teamName { get; set; }
     }

Controller

  public ActionResult Index()
        {
            MyteamViewModel ms = new MyteamViewModel ();
            var vm = (from u in db.Users
                     join tm in db.Team_Members
                     on u.user_id equals tm.user_id
                     join t in db.Teams
                     on tm.team_id equals t.team_id
                     orderby t.name
                     select new { fullName = u.firstName + u.lastName, teamName = t.name });
          //  var vmlist = vm.ToList();

            return View(vm);
        }

The view is type IEnumerable

@model IEnumerable<CTA2._0.ViewModels.ManageScoreViewModel>
@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.fullName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.teamName)
        </td>

I tried converting the query to a list(var vmlist = vm.ToList();). Didn't work. Any help would be appreciated.

like image 903
shinra tensei Avatar asked Oct 23 '12 18:10

shinra tensei


1 Answers

Your view is strongly typed to ManageScoreViewModel collection but your linq query is returning an anonymous object using projection. You need to return a list of ManageScoreViewModel objects. You can also apply ToList() method on the linq expression

Change

select new { fullName = u.firstName + u.lastName, teamName = t.name });

to

select new ManageScoreViewModel { fullName = u.firstName + u.lastName,
                                                  teamName = t.name }).ToList();
like image 183
Shyju Avatar answered Oct 17 '22 04:10

Shyju