2012-02-03 21 views
6

Quiero crear una extensión simple de HtmlHelper.ActionLink que agrega un valor al diccionario de valor de ruta. Los parámetros serían idénticas a HtmlHelper.ActionLink, es decir .:Agregar a routeValues ​​en el método de extensión HtmlHelper

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); 
} 

La lógica para lo que estoy añadiendo a routeValues es un poco prolijo, de ahí mi deseo de ponerlo en un ayudante método de extensión en lugar de repetir en cada vista.

tengo una solución que parece estar funcionando (publicado como una respuesta más abajo), pero:

  • Parece ser complicado innecesariamente para una tarea tan sencilla.
  • Todo el casting me parece frágil, como que hay algunos casos extremos en los que voy a estar causando una NullReferenceException o algo así.

Por favor, publique cualquier sugerencia de mejora o mejores soluciones.

Respuesta

10
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); 
} 
+0

Si usted está interesado, me han hecho esta pregunta que se relaciona con esta respuesta: http://stackoverflow.com/questions/9595334/correctly-making-an-actionlink-extension-with-htmlattributes –

Cuestiones relacionadas