i have this LINQ query on two tables
public ViewResult data()
{
var query = from a in DB.Album
join b in DB.Artists
on a.ArtistId equals b.ArtistId
where (b.ArtistId == 2)
select new { a ,b };
return View(query.ToList());
}
however i am confused how do i display these data i.e Artist table’s Artist name and Album tables Album Name in my view?
i am trying something like this but it gives me a error
@model IEnumerable<test1.Models.Album>
@{
ViewBag.Title = "data";
}
<h2>data</h2>
@Model.Count()
<br />
<ul>
@foreach (var mod1 in Model)
{
<li>
@* @mod1.Genre.Name*@
@Html.DisplayFor(modelItem => mod1.Artist.Name)
<br />
@mod1.AlbumId
<br />
@mod1.Artist
<br />
@mod1.Title
</li>
}
</ul>
Error i get is
The model item passed into the dictionary is of type ‘System.Collections.Generic.List1[<>f__AnonymousType1
2[test1.Models.Album,test1.Models.Artist]]’,
but this dictionary requires a model item of type ‘System.Collections.Generic.IEnumerable`1[test1.Models.Album]’.
Any idea ?
You are getting the exception because you are trying to pass a list of anonymous objects
instead of a list of albums.
You can create a viewmodel so you can use that type as your model.
Use this type when you return values from the query.
Then you should strongly type your view to this type and edit the view according to your viewmodel.