Search code examples
c#razor

C# Generics, what am I doing wrong?


I'm some what new to Generics and I can't figure out why the following doesn't work.

I have an extension to IEnumerable<T>, called Grid and it looks like so

  public static class IEnumerableGridExtension
  {
        public static HelperResult Grid<T>(this IEnumerable<T> gridItems, Action<GridView<T>> thegrid) 
        {
            ........
        }
   }

Say, I have a variable in my razor Model called "Products" and it is the type List<Product>, so I tried to do

@Model.Products.Grid<Product>(grid => {
...
});

I get an error:

Cannot convert method group 'Grid" to non-delegate type 'object'. Did you intend to invoke the method?

with @Model.tasks.Grid underlined in red.

The funny thing is, Visual Studio compiles, everything is fine. Of course, if I simply do

@Model.Products.Grid(grid => {
...
});

It's all fine.


Solution

  • The Razor parser is interpreting < and > as normal HTML tags. You can avoid the problem wrapping the call in parenthesis:

    @(Model.Products.Grid<Product>(grid=>{
    ...
    }))
    

    You can find additional info here: How to use generic syntax inside a Razor view file?