I want to create a simple extension of HtmlHelper.ActionLink that adds a value to the route value dictionary. The parameters would be identical to HtmlHelper.ActionLink, i.e.:
public static MvcHtmlString FooableActionLink(
this HtmlHelper html,
string linkText,
string actionName,
string controllerName,
object routeValues,
object htmlAttributes)
{
// Add a value to routeValues (based on Session, current Request Url, etc.)
// object newRouteValues = AddStuffTo(routeValues);
// Call the default implementation.
return html.ActionLink(
linkText,
actionName,
controllerName,
newRouteValues,
htmlAttributes);
}
The logic for what I am adding to routeValues is somewhat verbose, hence my desire to put it in an extension method helper instead of repeating it in each view.
I have a solution that seems to be working (posted as an answer below), but:
- It seems to be unnecessarily complicated for such a simple task.
- All the casting strikes me as fragile, like there are some edge cases where I’m going to be causing a NullReferenceException or something.
Please post any suggestions for improvement or better solutions.
1 Answer