2012-11-26 29 views
2

我正在尝试使用图像为ActionLink帮助程序创建扩展方法。带路由值的帮助程序的C#扩展方法

这是我的扩展方法:

public static class MyHelpers 
    { 
     public static string ActionLinkWithImage(this HtmlHelper html, string imgSrc, string actionName) 
     { 
      var urlHelper = new UrlHelper(html.ViewContext.RequestContext); 

      string imgUrl = urlHelper.Content(imgSrc); 
      TagBuilder imgTagBuilder = new TagBuilder("img"); 
      imgTagBuilder.MergeAttribute("src", imgUrl); 
      string img = imgTagBuilder.ToString(TagRenderMode.SelfClosing); 

      string url = urlHelper.Action(actionName); 

      TagBuilder tagBuilder = new TagBuilder("a") 
      { 
       InnerHtml = img 
      }; 

      tagBuilder.MergeAttribute("href", url); 

      return tagBuilder.ToString(TagRenderMode.Normal); 
     } 
    } 

和IM尝试使用这样的:

@Html.ActionLinkWithImage("Images/del.png", "Delete", new { id = item.ItemID}); 

但我的扩展方法不具有 '路径的值'。我如何实现这个?

+0

您定义的扩展方法有两个参数,但你用三个参数来调用它......这没有任何意义。 –

+1

这是毫无意义的得到snippy。既然你“显然”注意到了你的错误,那么为什么首先要问这个问题呢? –

+0

问题是/是如何实现路由的东西。我没有谈论任何编译器或运行时错误。事实上,我根本没有提到'错误'。你在说什么? – Yustme

回答

3

像这样:

public static string ActionLinkWithImage(this HtmlHelper html, string imgSrc, string actionName, object routeValues) 
    { 

    //Your code ... 

    string url = urlHelper.Action(actionName, routeValues); 

    } 
+0

谢谢,这是诀窍! – Yustme

2

添加对象参数的方法

, object routeData) 

,并把它传递给UrlHelper

new UrlHelper(new RequestContext(html.ViewContext.HttpContext, routeData))