Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 2/.NET 4/Razor - Can't use Any() extension method on a ViewModel member

I'm trying out the Razor ViewEngine from ASP.NET MVC 3 Preview 1 and I'm running into an issue trying to using the Any() extension method.

Here's the code I use to set the property in the controller:

ViewModel.Comparisons = DB.Comparisons.Where(c => c.UserID == this.UserID).ToArray();

Here's the code in the View where I try to use Any():

@if (!View.Comparisons.Any()) {
<tr>
    <td>You haven't not started any comparisons yet. @Html.Action("Start a new comparison?", "create", "compare")</td>
</tr>
}

I get an exception that says:

'System.Array' does not contain a definition for 'Any'

I've tried adding the System.Linq namespace to both the pages\namespaces section of web.config, and adding a @using System.Linq line at the top of the view, neither of which made a difference. What do I need to do to have access to the LINQ extension methods?

Update: It looks like it has to do with the fact that it's a property of a dynamic object - it works if I manually cast it to IList<T>.

like image 601
Daniel Schaffer Avatar asked Feb 26 '23 10:02

Daniel Schaffer


1 Answers

Unfortunately you cannot call extension methods on values that are declared as dynamic. In this case ViewModel returns dynamic values, so the compiler doesn't know the type, so calls to extension methods cannot be found.

I recommend one of the following:

  1. Use a strongly-typed view. This way you will also get full Intellisense in Visual Studio, once that is supported.

  2. Cast the values to IList explicitly and then call the extension method. This way the compiler can do the right mapping.

like image 161
Eilon Avatar answered Apr 25 '23 12:04

Eilon