[RESOLVED]The model item passed into the dictionary is of type 'System.Collections.Generic.List`1 – Try to do a orderby in my controller from two table.

I have two table defined bellow and I have a controller. I’m trying to return a set of grid that are ordered by location and I’m getting the following error: Need help.  What is wrong with my controller?

Table: MasterList

ID int Pimary Key

LastName VarChar

FirstName Varchar

LocationID Int This is the foreign key related to the PhoneListLocation table by its primary ID key

Table: PhoneListLocation

ID Int PrimaryKey

Location Varchar

So I want a data grid that dispay the following info

LastName  FirstName Location   and its ordered by location

Here is my controller

 

public
ActionResult
Index()

        {

         var masterLists = (from r in db.MasterLists.Include(m => m.PhoneListLocation)
   orderby r.PhoneListLocation.ID
   select r.PhoneListLocation);
// Not this – return View(masterLists.ToList());
// Use this instead:
return View(masterLists);

        }

Here is my View Index

@model IEnumerable<WebApplicationCodeFirstPhoneList.Models.MasterList>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.PhoneListLocation.Location)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Department)
        </th>
      </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.PhoneListLocation.Location)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Department)
        </td>
               <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.RecordID }) |
            @Html.ActionLink("Details", "Details", new { id=item.RecordID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.RecordID })
        </td>
    </tr>
}

</table>

Try using View models instead of using a var list into your view.

Create a view model and map it to that model and then use in your view.

http://www.dotnet-tricks.com/Tutorial/mvc/QHQT270712-Understanding-ViewModel-in-ASP.NET-MVC.html

Leave a Reply