ASP.NET MVC 2 / .NET 4 / Razor - cannot use the Any () extension method for the ViewModel

I am trying to run Razor ViewEngine from ASP.NET MVC 3 Preview 1 and I am having a problem using the Any() extension method.

Here is the code that I use to set the property in the controller:

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

Here is the code in the view where I am trying 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 tried to add the System.Linq namespace to the pages\namespaces section in the web.config file and add the @using System.Linq line at the top of the view, none of which changed the situation. What do I need to do to access LINQ extension methods?

Update: It seems that this is due to the fact that it is a property of a dynamic object - it works if I manually dropped it on IList<T> .

+4
source share
2 answers

Unfortunately, you cannot call extension methods for values ​​declared as dynamic. In this case, the ViewModel returns dynamic values, so the compiler does not know the type, so calls to extension methods cannot be found.

I recommend one of the following:

  • Use a strongly typed representation. This way you will also get full Intellisense in Visual Studio, if supported.

  • Enter the values ​​in the IList explicitly, and then call the extension method. In this way, the compiler can do the correct mapping.

+8
source

This seems to be a bug with the dynamic view. If you change the @if instruction to something like

 @if(!(new List<string>().Any())) { } 

You will see that it works.

0
source

All Articles