ASP.NET MVC List of Anonymous Classes Raises Error in Count () Method

I have a serveride code where I return a list of an anonymous class from the database:

    public ActionResult DisplayMap()
    {
        ViewBag.Checkins = (from locationUpdate in db.LocationUpdates
                            select new
                            {
                                locationUpdate,
                                locationUpdate.User
                            }).ToList();
        return View();
    }

On the Razor page, I want to get a count of this list:

@if (ViewBag.Checkins.Count() > 0)
{ ... }

However, this causes an error:

An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred 
in System.Core.dll but was not handled in user code.

Additional information: 'object' does not contain a definition for 'Count'

When I type ViewBag.Checkinsin the direct window, I get:

ViewBag.Checkins
{System.Collections.Generic.List<<>f__AnonymousType6<MY_APP.LocationUpdate,MY_APP.User>>}
    [0]: { locationUpdate = {System.Data.Entity.DynamicProxies.LocationUpdate_4532566693B61EF657DDFF4186F1D6802EA1AC8D5267ED245EB95FEDC596E129}, User = {System.Data.Entity.DynamicProxies.User_816C8A417B45FE8609CD1F0076A5E6ECBAB0F309D83D2F8A7119044B1C6060CF} }

The object Checkinsreally is Listand the data is correct. I tried Count, Lengthtoo (without calling the method as a property), but no luck. What am I doing wrong?

+4
source share
4 answers

ViewBag dynamic, Count - , ( ).

IEnumerable<dynamic>, :

@if (((IEnumerable<dynamic>)ViewBag.Checkins).Count() > 0)

@if (Enumerable.Count(ViewBag.Checkins) > 0)

Checkins ViewBag.

, count 0, Any ( ):

@if (Enumerable.Any(ViewBag.Checkins))
+14

, , . .

, - :

public class MyViewModel{
LocationUpdate LocationUpadte{get;set;}
User User{get;set;}
}

public ActionResult DisplayMap()
{
        var model = (from locationUpdate in db.LocationUpdates
                            select new MyViewModel
                            {
                                locationUpdate,
                                locationUpdate.User
                            }).ToList();
        return View(model);
}

@Model.Count()

+1

You need to cast your object since the viewbag is dynamic. For instance:

var list = ViewBag.List as List<int>();
list.Count();
0
source

You can do it:

- @if(ViewBag.Checkins.Count > 0)
-3
source

Source: https://habr.com/ru/post/1538587/


All Articles