WebGrid Column Format Issue in MVC3

Rory McCrossan picture Rory McCrossan · Mar 22, 2011 · Viewed 19.8k times · Source

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?

Answer

Darin Dimitrov picture Darin Dimitrov · Mar 22, 2011

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.