我正在尝试为带有图像的ActionLink
助手制作一个扩展方法。
这是我的扩展方法:
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);
}
}
我试图像这样使用它:
@Html.ActionLinkWithImage("Images/del.png", "Delete", new { id = item.ItemID});
但是我的扩展方法没有"路由值"。我该如何实现?
像这样:
public static string ActionLinkWithImage(this HtmlHelper html, string imgSrc, string actionName, object routeValues)
{
//Your code ...
string url = urlHelper.Action(actionName, routeValues);
}
向方法中添加对象参数
, object routeData)
并将其传递给 UrlHelper
new UrlHelper(new RequestContext(html.ViewContext.HttpContext, routeData))