2012-02-03 3 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 –

관련 문제