2012-02-03 25 views
6

Rota değeri sözlüğüne bir değer ekleyen HtmlHelper.ActionLink basit bir uzantı oluşturmak istiyorum. parametreleri, HtmlHelper.ActionLink için yani .: özdeş olacaktırHtmlHelper uzantısı yönteminde routeValues ​​öğesine ekleme

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

ne routeValues ekleyerek ediyorum her görünümünde tekrar yerine bir uzantısı yöntemi yardımcı koymak arzum dolayısıyla biraz ayrıntılı olduğu için mantık.

ben çalışıyor gibi görünüyor bir çözüm (aşağıda bir cevap olarak yayınlanmıştır) var, ama:

  • gereksiz gibi basit bir görev için karışık gibi görünüyor.
  • Tüm dökümler beni NullReferenceException veya bir şeylere neden olacağım bazı uç durumlar gibi kırılgan olarak vurur.

Lütfen iyileştirme veya daha iyi çözümler için önerilerinizi gönderin. Eğer ilgileniyorsanız

cevap

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

, bu cevap ile ilgilidir bu soruyu sordum: http://stackoverflow.com/questions/9595334/correctly-making-an-actionlink-extension-with-htmlattributes –

İlgili konular