Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Html.ActionLink render "?Length=4"

Tags:

asp.net-mvc

I'm VERY confused as to why this code

Html.ActionLink("About", "About", "Home", new { hidefocus = "hidefocus" }) 

results in this link:

<a hidefocus="hidefocus" href="/Home/About?Length=4">About</a> 

The hidefocus part is what I was aiming to achieve, but where does the ?Length=4 come from?

like image 855
My Alter Ego Avatar asked May 05 '09 10:05

My Alter Ego


People also ask

How does HTML ActionLink work?

Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.

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.

How do you change the ActionLink color in HTML?

@Html. ActionLink("name", "Action", "Controler", new { id= sentId, Style = "color:White" }, null);

How do I pass an object in ActionLink?

If you need to pass through the reference to an object that is stored on the server, then try setting a parameter of the link to give a reference to the object stored on the server, that can then be retrieved by the action (example, the Id of the menuItem in question).


2 Answers

The Length=4 is coming from an attempt to serialize a string object. Your code is running this ActionLink method:

public static string ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, object htmlAttributes) 

This takes a string object "Home" for routeValues, which the MVC plumbing searches for public properties turning them into route values. In the case of a string object, the only public property is Length, and since there will be no routes defined with a Length parameter it appends the property name and value as a query string parameter. You'll probably find if you run this from a page not on HomeController it will throw an error about a missing About action method. Try using the following:

Html.ActionLink("About", "About", new { controller = "Home" }, new { hidefocus = "hidefocus" }) 
like image 114
roryf Avatar answered Oct 24 '22 19:10

roryf


The way I solved this is was adding a null to the fourth parameter before the anonymous declaration (new {}) so that it uses the following method overload: (linkText, actionName, controllerName, routeValues, htmlAttributes):

Html.ActionLink("About", "About", "Home", null, new { hidefocus = "hidefocus" }) 
like image 37
Manuel Castro Avatar answered Oct 24 '22 19:10

Manuel Castro