Rukshar Khan Rukshar Khan - 6 months ago 29
C# Question

MVC Issue model item passed

I am getting this error when running my project:


The model item passed into the dictionary is of type
'System.Collections.Generic.List
1[<>f__AnonymousType12
1[System.Int32]]',
but this dictionary requires a model item of type
'System.Collections.Generic.IEnumerable`1[SIMS.Models.IAMarksheetResult]'.


Controller

public ActionResult Index()
{
var IAMark =
_context.IAMarksheetResults
.Select (x => new { x.GUId }).Distinct()
.ToList();

return View(IAMark.ToList());
}


View

@model IEnumerable<Models.IAMarksheetResult>

@{
ViewBag.Title = "Index";
}

<h2>IA Marksheet </h2>
<p>
@Html.ActionLink("Upload IA Marksheet", "MarksheetUpload")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.GUId)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.GUId)
</td>
<td>
@Html.ActionLink("Delete", "Delete", new { id = item.GUId })
</td>
</tr>
}
</table>

Answer Source

You are passing an anonymous type on your View with this code:

var IAMark =
      _context.IAMarksheetResults
     .Select (x => new  { x.GUId }).Distinct()  //This converts your list to anonymous type
     .ToList();

If you want distinct and still passing the expected model, you can do this:

var IAMark =
      _context.IAMarksheetResults
     .GroupBy(x => x.GUId ).Select(x => x.FirstOrDefault())
     .ToList();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download