On an ASP.NET MVC project I’ve been working on recently we were experiencing some odd behaviour. We had an ActionLink, like:
@Html.ActionLink("Click here to subscribe", "Subscribe", "News")
Then we wanted to add a CSS class to the link tag, so we did this:
@Html.ActionLink("Click here to subscribe", "Subscribe", "News", new { @class = "hightlight" })
But we started getting some very odd behaviour; the link’s URL would be appended with: ?length=4
At first I couldn’t figure it out, but then I noticed the cause of the problem thanks to the IDE’s tooltip.
My first link called the following helper method:
public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName
)
But my second link called this helper method:
public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
Object routeValues,
Object htmlAttributes
)
You can see that the parameter for controllerName has changed to routeValues. To resolve this I’ve had to change my link to:
@Html.ActionLink("Click here to subscribe", "Subscribe", "News", null, new { @class = "hightlight" })
So that it now calls:
public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
Object routeValues,
Object htmlAttributes
)
This caused me a good bit of grief, especially that the project compiled ok. You would think that the guys behind MVC would try and maintain some consistency in regards to method overloads? Anyways, I’m not trying to portray ASP.NET MVC as bad, I honestly think it’s an awesome product - just with this little annoyance.
While I was writing this post I found a question on Stack Overflow, where one refered to it an example of “overload hell” in ASP.NET MVC.