匿名类的ASP.NET MVC ViewBag列表在Count()方法上引发错误



我有一个服务器端代码,在这里我从数据库返回一个匿名类的列表:

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

在Razor页面,我想得到这个列表的计数:

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

然而,它抛出了一个错误:

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'

当我在即时窗口中键入ViewBag.Checkins时,我得到:

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} }

Checkins对象实际上是List,并且数据是正确的。我也尝试过CountLength(没有方法调用,只是作为属性),但没有成功。我做错了什么?

ViewBagdynamic,而Count扩展方法,不受动态支持(必须在编译时绑定)。

您可以转换为IEnumerable<dynamic>:

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

或者直接使用静态方法:

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

或者创建一个具有Checkins属性的强类型模型,并完全避免ViewBag

编辑

由于您只是想检查计数是否大于0,因此Any更合适(根据情况可能会节省一些处理时间):

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

viewbag是动态的,这使它成为内部生成的匿名类型。最好使用视图模型。

然后用它的模型调用视图,这样做:

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()将返回预期值

由于viewbag是动态的,因此需要投射对象。例如:

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

您可以这样做:

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

最新更新