2012-02-03 100 views
6

我想创建一个简单的扩展HtmlHelper.ActionLink,它为路由值字典添加一个值。该参数是相同HtmlHelper.ActionLink,即:附加到HtmlHelper扩展方法中的routeValues

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

什么我加入到routeValues有点冗长,因此我希望把它放在一个扩展方法帮手,而不是在每个视图重复它的逻辑。

我有一个似乎是工作的解决方案(如贴在下面的答案),但:

  • 这似乎是不必要的复杂,这样一个简单的任务。
  • 所有的投射都让我感到脆弱,就像有一些边缘情况会导致NullReferenceException或其他问题。

请发布任何改进建议或更好的解决方案。

回答

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

如果你有兴趣,我问这个问题是与这个答案︰http://stackoverflow.com/questions/9595334/correctly-making-an-actionlink-extension-with-htmlattributes – 2012-03-07 05:13:48

相关问题