2012-02-03 18 views
6

Tôi muốn tạo một phần mở rộng đơn giản là HtmlHelper.ActionLink để thêm giá trị vào từ điển giá trị tuyến đường. Các thông số sẽ giống với HtmlHelper.ActionLink, tức là .:Nối vào các giá trị trong phương thức mở rộng 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); 
} 

Logic cho những gì tôi đang làm tăng thêm routeValues là hơi dài dòng, vì vậy mong muốn của tôi để đặt nó trong một helper phương pháp mở rộng thay vì lặp lại nó trong từng xem.

Tôi có một giải pháp mà dường như được làm việc (được đăng như một câu trả lời dưới đây), nhưng:

  • Nó có vẻ được phức tạp cho một nhiệm vụ đơn giản như vậy.
  • Tất cả các cuộc đình công đúc tôi đều mong manh, như có một số trường hợp cạnh mà tôi sẽ gây ra một NullReferenceException hoặc một cái gì đó.

Vui lòng gửi bất kỳ đề xuất nào để cải thiện hoặc giải pháp tốt hơn.

Trả lời

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

Nếu bạn quan tâm, tôi đã hỏi câu hỏi này có liên quan đến câu trả lời này: http://stackoverflow.com/questions/9595334/correctly-making-an-actionlink-extension-with-htmlattributes –

Các vấn đề liên quan