Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor does not work easily with strongly typed Html.ActionLink?

Folks,

We are trying to use the strongly typed action link methods that look like this:

Html.ActionLink<HomeController>

in the Razor view engine.

I know we shouldn't use them all the time because it ignores filters, etc., but the fact is we do use them.

If I try to use this directly in Razor like so:

@Html.ActionLink<HomeController>(c => c.Index, "Home")

I get an error of:

CS1502: The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments

If you look at the compiled code, it's because Razor is not parsing that statement as you would expect. The compiled source, from the error that has the line looks like this:

...
Line 101:              #line 13 "C:\dev\TheNetwork\POC\Web\Views\Policy\Edit.cshtml"
Line 102:  Write(Html.ActionLink);
Line 103:  
Line 104:              
Line 105:              #line default
Line 106:              #line hidden
Line 107:  WriteLiteral("<PolicySectionController>(c => c.Edit(null), "New\")\r\n\r\n\r\n\r\n");

Much stuff omitted for brevity :) As you can see, it splits it on the "<" I think it's interpreting that as an HTML tag, but I can't be sure.

I found a workaround, but it's ugly. This works:

@{Write(Html.ActionLink<PolicySectionController>(c => c.Edit(null), "New"));}

Does anyone know of a better way to do this?

like image 710
CubanX Avatar asked Nov 11 '10 21:11

CubanX


People also ask

What is HTML ActionLink ()?

ActionLink(HtmlHelper, String, String, String, String, String, String, Object, Object) Returns an anchor element (a element) for the specified link text, action, controller, protocol, host name, URL fragment, route values, and HTML attributes.

What is difference between HTML ActionLink and URL action?

Yes, there is a difference. Html. ActionLink generates an <a href=".."></a> tag whereas Url. Action returns only an url.

What is Ajax ActionLink?

The Ajax. ActionLink() helper method returns an anchor element that contains the URL to the specified action method; when the action link is clicked, the action method is invoked asynchronously by using JavaScript.

How do I transfer my ActionLink model to my controller?

ActionLink is rendered as an HTML Anchor Tag (HyperLink) and hence it produces a GET request to the Controller's Action method which cannot be used to send Model data (object). Hence in order to pass (send) Model data (object) from View to Controller using @Html.


2 Answers

Yeah, in order to use generic methods you need to escape the expression using parens. Would this work:

@(Html.ActionLink<PolicySectionController>(c => c.Edit(null), "New"))
like image 52
marcind Avatar answered Oct 06 '22 19:10

marcind


I think you can also do: @Html.ActionLink((FooController c) => c.Edit(null), "New")

like image 26
mcintyre321 Avatar answered Oct 06 '22 19:10

mcintyre321