Add to routeValues ​​in the HtmlHelper extension method

I want to create a simple HtmlHelper.ActionLink extension that will add a value to the route's value dictionary. The parameters will be identical to HtmlHelper.ActionLink , HtmlHelper.ActionLink .:

 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 of what I add to routeValues is somewhat verbose, so my desire is to put it in an extension method helper instead of repeating it in every view.

I have a solution that seems to work (posted as an answer below), but:

  • For such a simple task it seems unnecessarily complicated.
  • All castings amaze me as fragile, for example, there are some cases when I will throw a NullReferenceException or something like that.

Please post any suggestions for improvements or better solutions.

+6
source share
1 answer
 public static MvcHtmlString FooableActionLink( this HtmlHelper html, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes) { // Convert the routeValues to something we can modify. var routeValuesLocal = routeValues as IDictionary<string, object> ?? new RouteValueDictionary(routeValues); // Convert the htmlAttributes to IDictionary<string, object> // so we can get the correct ActionLink overload. IDictionary<string, object> htmlAttributesLocal = htmlAttributes as IDictionary<string, object> ?? new RouteValueDictionary(htmlAttributes); // Add our values. routeValuesLocal.Add("foo", "bar"); // Call the correct ActionLink overload so it converts the // routeValues and htmlAttributes correctly and doesn't // simply treat them as System.Object. return html.ActionLink( linkText, actionName, controllerName, new RouteValueDictionary(routeValuesLocal), htmlAttributesLocal); } 
+10
source

Source: https://habr.com/ru/post/907571/


All Articles