2012-02-03 38 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

相關問題