In my ASP.NET MVC Core app, if I pass a LINQ Query result of either Query 1 and 2 below, I get following error. On the other hand if I pass result of LINQ Query 3, I get the view correctly displayed without any error. But query 3 is sending all the columns of the Blogs table and I want to send only the columns that I want displayed in the view. Question: How can I avoid the below error while sending only the columns to the view that I want to be displayed in the View?
Note: I want to avoid using a ViewModel since I'm using only one table in the LINQ Queries. Also, obviously the query is sent from an Action method that I've not included for here for brevity:
Error:
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List'1[<>f__AnonymousType3`3[System.Int32,System.String,System.Boolean]]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.List'1[myProj.Models.Blog]'
LINQ Query 1:
var qry = from b in _context.Blogs
select new {b.BlogId, b.BlogName, b.IsNotified};
return View(await qry.ToListAsync());
LINQ Query 2:
var qry = from b in _context.Blogs
select new { BlogId= b.BlogId, BlogName= b.BlogName, IsNotified = b.IsNotified};
return View(await qry.ToListAsync());
LINQ Query 3:
var qry = from b in _context.Blogs
select b;
return View(await qry.ToListAsync());
View:
@model List<myProj.Models.Blogs>
<form asp-controller="DbRelated" asp-action="BlogsReview" method="post">
<table class="table">
<thead>
<tr>
<th></th>
<th>
Blog Name
</th>
<th>
Is Notified
</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>@Html.HiddenFor(r => r[i].BlogId)</td>
<td>
@Html.EditorFor(r => r[i].BlogName)
</td>
<td>
@Html.CheckBoxFor(r => r[i].IsNotified)
</td>
</tr>
}
</tbody>
</table>
<button type="submit" class="btn btn-default">Save</button>
</form>