views:

256

answers:

2

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

A: 

It appears to be a bug with the dynamic View property. If you change your @if statement to something like

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

You'll see that it works.

BuildStarted
+2  A: 

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.

Eilon
That's really interesting and it makes perfect sense now...I think I still view dynamic as not much more than a `var`. Thanks for that. :)
BuildStarted