views:

306

answers:

2

Can anyone explain why the following happens? And how to resolve, Visual Studio 2010 and MVC2

<%= Html.ActionLink("Add New Option", "AddOption", "Product", new { @class = "lighbox" }, null)%>

Results in

/Product/AddOption?class=lightbox

<%= Html.ActionLink("Add New Option", "AddOption", "Product", new { @class = "lighbox" })%>

Results in

/Product/AddOption?Length=7

Thanks

+6  A: 

You're using these respective overloads:

public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
Object routeValues,
Object htmlAttributes
)

From: http://msdn.microsoft.com/en-us/library/dd504972.aspx

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

From: http://msdn.microsoft.com/en-us/library/dd492124.aspx

The first new { @class = "lighbox" } is passed as the routeValues argument when it should be the htmlAttributes argument.

This sort of problem is common with the extension methods used in MVC. In can sometimes help to use named arguments (C# 4.0) to make things more readable:

<%= Html.ActionLink(linkText: "Add New Option", 
   actionName: "AddOption",
   controllerName: "Product", 
   htmlAttributes: new { @class = "lighbox" }, 
   routeValues: null)%>
David Neale
+2  A: 

This is an example of "overload hell" in ASP.NET MVC.

The first code calls the following method:

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    Object routeValues,
    Object htmlAttributes
)

whereas the second code calls this one:

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

Notice that the string parameter controllerName in the first call is becoming routeValues in the second one. The string value "Product" is being passed to the routed values: the string property Length is used, which has a length of 7 here, hence the "Length=7" you're getting in the route.

Considering the first method, it seems that you've swapped the routeValues and htmlAttributes parameters.

Julien Lebosquain