VBK
VBK

Reputation: 23

ASP.NET MVC3 - Usage of Html.ActionLink

I need to use the Html.ActionLink in the format: property of the grid.Column specification. My code goes as below:

grid.GetHtml(

  grid.Columns( 
    grid.Column(header: "Column 1", format: (item) => @<div class='webgrid-bookname-column-style'> @item.BookName </div>),
    grid.Column(header: "Column 2", format: (item) => Html.ActionLink(item.StartTime, "ShowShippingFileMessage", new { @id = item.BookName }))
  )
)

When I use this syntax, it gives me the compilation error of The best overloaded method match for System.Web.Helpers.WebGrid.Column(string, string, System.Func<dynamic,object>, string, bool) has some invalid arguments When I change the item.StartTime above with a normal text like "Edit" then it works fine.

I am new to ASP.NET, can anyone please help me understand what is wrong with the above statements?

Thanks in advance.

Upvotes: 2

Views: 1227

Answers (2)

amesh
amesh

Reputation: 1319

The display string you are passing is of the type DateTime. Try giving String Input.

grid.Column(header: "Column 2", format: (item) => Html.ActionLink(item.StartTime.ToString(), "ShowShippingFileMessage", new { @id = item.BookName }))

Upvotes: 0

SLaks
SLaks

Reputation: 887451

The format parameter is of type Func<dynamic, HelperResult>.
It must return a HelperResult, not an IHtmlString.
It is defined this way to allow you to pass an inline helper.
To pass an inline helper, remove (item) =>; inline helpers implicitly generate a lambda expression with an item parameter.
To pass a normal lambda expression, you need to make it return a HelperResult instance.
HelperResults take an Action<TextWriter>, so you would write

item => new HelperResult(w => w.Write(Html.ActionLink(...).ToHtmlString()))

EDIT: I hadn't realized that the parameter is declared as Func<dynamic, object>. That means you can either pass an inline helper or any other lambda expression.
Your second example ought to work.

You can also use an inline helper. To do that without an HTML tag, use the special <text> tag:

item => @<text>@Html.ActionLink(...)</text>

Razor will drop the <text> from the output.

Upvotes: 1

Related Questions