Why can't I use my extension method in a delegate in the Razor WebGrid
asp.net-mvc, c#, webgrid
Solution
This is not a limitation of the WebGrid or Razor. It's a limitation of the C# `dynamic` type. You cannot use extension methods on dynamic. The format helper takes a `Func<dynamic, object>` as an argument, so the `item` parameter is a dynamic type.
I wrote about this exact issue a couple of years ago.
Problem
I'm using the MVC 3 introduced WebGrid, but can't can't apply my own extension methods when passing a delegate for the `format` param. Using: ``` Grid.Column("MyProperty", "MyProperty", format: @<span class="something">@item.MyProperty.MyExtensionMethodForString()</span>) ``` I got ``` ERROR: 'string' does not contain a definition for 'MyExtensionMethodForString' ``` I've tried casting, not to avail ``` Grid.Column("MyProperty", "MyProperty", format: @<span class="something">@((string)(item.MyProperty).MyExtensionMethodForString())</span>) ``` If I use an standard method, it works: ``` Grid.Column("MyProperty", "MyProperty", format: @<span class="something">@(Utils.MyExtensionMethodForString(item.MyProperty))</span>) ``` I've also tried to put the extension in the same namespace, with no results. How can I use my beloved extensions? Edit: The namespace per se it's not the problem, the namespace where the extension is available for all the views and classes, and I can use it in the same view without problem. The problem is when using it in the delegate.