ViewBag is dynamic and the problem is that the anonymous type is generated as internal. I would recommend you using a view model or you should strong typed the ViewBag in foreach loop.
Hope this helpful
Regards
Please mark the replies as answers if they help or unmark if not.
Feedback to us
CharlyB
Member
4 Points
24 Posts
Anonymous types in LINQ Select New. TROUBLE.
May 18, 2012 12:47 AM|LINK
ViewBag.result =
(from row in _db.Productions
orderby row.IdProduction descending
select new { row.IdProduction, row.Image }).Take(10);
And then in View:
@foreach (var n in ViewBag.result)
{
n.IdProduction - n.Image
}
Error, like "n" is not an object.
But when im makin:
@foreach (var n in ViewBag.result)
{
n
}
On final page Im getting list of items like:
{Id = ##, Image = "Image##"}
Seems like its "n" values, but how to make n.Id and n.Image ???
Tnx.
urenjoy
Star
12367 Points
1862 Posts
Re: Anonymous types in LINQ Select New. TROUBLE.
May 18, 2012 01:06 AM|LINK
Try following
@(n.GetType().GetProperty("IdProduction").GetValue(n,null) +" -" + n.GetType().GetProperty("Image").GetValue(n,null))Check another example to access anonymous type property in gridview sorting
http://techbrij.com/926/anonymous-type-linq-gridview-sorting-asp-net
CharlyB
Member
4 Points
24 Posts
Re: Anonymous types in LINQ Select New. TROUBLE.
May 18, 2012 02:45 AM|LINK
It works, but why it dont work with usual method ?
Maybe I need to find how to convert Anonymous types to IQeryable or something like that ?
Young Yang -...
All-Star
21343 Points
1818 Posts
Microsoft
Re: Anonymous types in LINQ Select New. TROUBLE.
May 24, 2012 12:19 PM|LINK
Hi
ViewBag is dynamic and the problem is that the anonymous type is generated as internal. I would recommend you using a view model or you should strong typed the ViewBag in foreach loop.
Hope this helpful
Regards
Feedback to us
Develop and promote your apps in Windows Store
CharlyB
Member
4 Points
24 Posts
Re: Anonymous types in LINQ Select New. TROUBLE.
May 24, 2012 01:36 PM|LINK
I made it, but in way of creating a new model for my data from Select.