在MVC3中使用剃刀替换图像链接的最好方法是什么?我现在只是简单地这样做:
<a href="@Url.Action("Edit", new { id=MyId })"><img src="../../Content/Images/Image.bmp", alt="Edit" /></a>
有没有更好的方法?
发布于 2011-02-05 03:14:42
您可以为HtmlHelper创建一个扩展方法,以简化CSHTML文件中的代码。您可以使用如下方法替换您的标记:
// Sample usage in CSHTML
@Html.ActionImage("Edit", new { id = MyId }, "~/Content/Images/Image.bmp", "Edit")
下面是上述代码的扩展方法示例:
// Extension method
public static MvcHtmlString ActionImage(this HtmlHelper html, string action, object routeValues, string imagePath, string alt)
{
var url = new UrlHelper(html.ViewContext.RequestContext);
// build the <img> tag
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttribute("src", url.Content(imagePath));
imgBuilder.MergeAttribute("alt", alt);
string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
// build the <a> tag
var anchorBuilder = new TagBuilder("a");
anchorBuilder.MergeAttribute("href", url.Action(action, routeValues));
anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(anchorHtml);
}
发布于 2011-02-04 21:52:53
您可以使用Url.Content
,它适用于所有链接,因为它将代字号~
转换为根uri。
<a href="@Url.Action("Edit", new { id=MyId })">
<img src="@Url.Content("~/Content/Images/Image.bmp")", alt="Edit" />
</a>
发布于 2012-07-31 10:28:20
基于卢卡斯上面的回答,这是一个接受控制器名称作为参数的重载,类似于ActionLink。当您的图像链接到不同控制器中的Action时,请使用此重载。
// Extension method
public static MvcHtmlString ActionImage(this HtmlHelper html, string action, string controllerName, object routeValues, string imagePath, string alt)
{
var url = new UrlHelper(html.ViewContext.RequestContext);
// build the <img> tag
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttribute("src", url.Content(imagePath));
imgBuilder.MergeAttribute("alt", alt);
string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
// build the <a> tag
var anchorBuilder = new TagBuilder("a");
anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(anchorHtml);
}
https://stackoverflow.com/questions/4896439
复制相似问题