dav*_*avy 118 action image razor asp.net-mvc-3
在MVC3中使用Razor替换图像链接的最佳方法是什么.我现在只是这样做:
<a href="@Url.Action("Edit", new { id=MyId })"><img src="../../Content/Images/Image.bmp", alt="Edit" /></a>
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?
Luc*_*cas 216
您可以为HtmlHelper创建扩展方法,以简化CSHTML文件中的代码.您可以使用以下方法替换标记:
// Sample usage in CSHTML
@Html.ActionImage("Edit", new { id = MyId }, "~/Content/Images/Image.bmp", "Edit")
Run Code Online (Sandbox Code Playgroud)
以下是上述代码的示例扩展方法:
// 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);
}
Run Code Online (Sandbox Code Playgroud)
jga*_*fin 63
您可以使用Url.Content哪个适用于所有链接,因为它将波浪号~转换为根uri.
<a href="@Url.Action("Edit", new { id=MyId })">
<img src="@Url.Content("~/Content/Images/Image.bmp")", alt="Edit" />
</a>
Run Code Online (Sandbox Code Playgroud)
Cra*_*ake 24
基于Lucas上面的答案,这是一个重载,它将控制器名称作为参数,类似于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);
}
Run Code Online (Sandbox Code Playgroud)
Adr*_*oRR 11
好吧,你可以使用@Lucas解决方案,但还有另一种方法.
@Html.ActionLink("Update", "Update", *Your object value*, new { @class = "imgLink"})
Run Code Online (Sandbox Code Playgroud)
现在,在CSS文件或页面中添加此类:
.imgLink
{
background: url(YourImage.png) no-repeat;
}
Run Code Online (Sandbox Code Playgroud)
使用该课程,任何链接都将具有您想要的图像.
| 归档时间: |
|
| 查看次数: |
130616 次 |
| 最近记录: |