WebGrid Column Format Issue in MVC3
Asked Answered
H

1

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?

Hodden answered 22/3, 2011 at 16:46 Comment(0)
F
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.

Fibriform answered 22/3, 2011 at 18:31 Comment(4)
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?Hodden
@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.Fibriform
It's always the best you get from Microsoft.Prescience
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.Applicative

© 2022 - 2024 — McMap. All rights reserved.