JNYRanger
JNYRanger

Reputation: 7097

Linq Failure during Razor Page Rendering - No Definition for Any

I'm receiving a RuntimeBinderException saying that System.Collections.Generic.List<string> does not contain a definition for Any. I have an IEnumerable<string> set within the dynamic ViewBag object called ValidationFailures. However, this exception is thrown within the Razor page calling:

@if(ViewBag.ValidationFailures.Any())
{ ... }

The IEnumerable is added in my controller before returning the view as seen below:

ViewBag.ValidationFailures = TempData.ContainsKey("ValidationFailures")
                ? (IEnumerable<string>)TempData["ValidationFailures"]
                : Enumerable.Empty<string>();

Normally, I'd chalk this up to missing a reference to Linq, but Linq is included within the web.config file within the View folder:

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization"/>
        <add namespace="System.Web.Routing" />
        <add namespace="System.Linq" />
        <add namespace="myProject" />
      </namespaces>
    </pages>
</system.web.webPages.razor>

For the hell of it I tried adding @using System.Linq to the top of the View as well, but this did not change the behavior. Linq queries are working fine in other views, but this single view is giving me an issue.

What else could cause this exception to be thrown?

Upvotes: 0

Views: 593

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100630

Properties of ViewBag are dynamic and you can't call extension methods that way.

You can explicitly cast to your type to make it possible:

  @if(((IEnumerable<string>)ViewBag.ValidationFailures).Any())

See Extension method and dynamic object for more info.

Upvotes: 2

Related Questions