C# – ASP.NET MVC3 WebGrid format: parameter

asp.net-mvc-3clambdawebgrid

I am trying to use the new WebGrid in ASP.NET MVC3 and one of the columns I want to display set of link icons that performs various actions (Edit, View, Delete)…
For this purpose I have a HtmlHelper extensions that basically outputs following HTML:

<a href="" title=""><img alt="" src="" /></a>

The extension returns MvcHtmlString and it works fine when used in Razor views by itself..Eg:
@Html.ActionLinkIconForEditAction("Customer", 2)

The issue is I need to invoke this helper (once for each action) in WebGrid column while passing the ID of the object. The problem that I am stumped on is that compiler gives me an error saying that it cannot convert MvcHtmlString (or 'lambda expression' depending on invocation I try) to System.Func expected by the format…

So for example, this works:

grid.Column(header: "", format: @<text>@Html.ActionLinkIconForEditAction("Customer", 2)</text>)

But this does not:

grid.Column(header: "", format: (customer) => @<text>@Html.ActionLinkIconForEditAction("Customer", customer.Id)</text>)
grid.Column(header: "", format: (customer) => Html.ActionLinkIconForEditAction("Customer", customer.Id))

I get:

Error 4 Argument 3: cannot convert from 'lambda expression' to 'System.Func<dynamic,object>'

or for this call:

grid.Column(header: "", format: Html.ActionLinkIconForEditAction("Customer", customer.Id)),

I get:

Error 5 Argument 3: cannot convert from 'System.Web.Mvc.MvcHtmlString' to 'System.Func<dynamic,object>'

What is weird I have other columns that ustilize lambdas, direct Model.Property accessors, and even output from String.Format("")…They all work fine…
I read all the docs on Func and this thread as well, and still can't quite figure it out 🙂

Can anyone spot what I am doing wrong?

Best Answer

I got it :) .... The issue appears to be in the way C# handles dynamic objects...Lots of users are having a blast with this...

The fix was as simple as casting a correct type on the parameter to my extension helper... So this works:

grid.Column(header: "", format: @<text>@Html.ActionLinkIconForEditAction("Customer", (int)item.Id)

The other trick is to use "built" in "item" object and not provide your own..So, for example, this does not work:

grid.Column(header: "", format: (customer) =>  @<text>@Html.ActionLinkIconForEditAction("Customer", (int)customer.Id)

Lots of reading, tweaking, learning... Hopefully, next version will have something a lot easier to use when you need to add content to columns that are not coming directly from the model...

Regards Z...

Related Topic