12

I've been trying to change the format of a single column in a WebGrid without much success. Said column is this:

grid.Column(
    columnName: "EmailAddress", 
    header: "Email Address", 
    format:(item) => Html.EmailLink(item.EmailAddress, item.EmailAddress, ""), 
    canSort: false
),

The error is:

The best overloaded method match for 'System.Web.Helpers.WebGrid.Column(string, string, System.Func, string, bool)' has some invalid arguments

I am confused as the method signature matches. Also, if I change the column to the below then it works without any errors:

grid.Column(
    columnName: "EmailAddress", 
    header: "Email Address", 
    format:(item) => new HtmlString(String.Format("<a href=\"mailto:{0}\" class=\"{2}\">{1}</a>", item.EmailAddress, item.EmailAddress, "")), 
    canSort: false
),

For reference, EmailLink is a very basic HtmlHelper extension method:

public static IHtmlString EmailLink(this HtmlHelper helper, string emailAddress, string linkText, string linkClass) {
    return new HtmlString(String.Format("<a href=\"mailto:{0}\" class=\"{2}\">{1}</a>", emailAddress, linkText, linkClass));
}

Can anyone tell me what the issue here is, and how I can solve it?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

1 Answers1

21

This is due to the ugliness of WebGrid and all this dynamic crap. You need a cast:

grid.Column(
    columnName: "EmailAddress", 
    header: "Email Address", 
    format: item => Html.EmailLink(
        (string)item.EmailAddress, 
        (string)item.EmailAddress, 
        ""
    ), 
    canSort: false
)

This being said don't hesitate to checkout MvcContrib Grid or the Telerik Grid which are far better.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    Perfect, this fixed the problem. I'm going to look at MvcContrib controls as this solution is very inelegant. I wasn't aware they had released anything Razor/MVC3 compatible yet though? – Rory McCrossan Mar 22 '11 at 19:52
  • 1
    @Rory McCrossan, the WebGrid was released with MVC 3 and it was supposed to work nicely with Razor, so that's the best you get from Microsoft at the moment. – Darin Dimitrov Mar 22 '11 at 19:54
  • 3
    It's always the best you get from Microsoft. –  Mar 24 '11 at 01:18
  • Is it possible to use a HtmlString for the header? I have been trying casting the HtmlString back to a string but the result is that the string is shown as plain html... I have been thinking to override the WebGrid, but I hope there is an easier way. Would be great if you could expand this answer so the HtmlString could be use for the header attribute. – thomvlau Nov 04 '13 at 16:09