动作图像MVC3 Razor [英] Action Image MVC3 Razor

查看:37
本文介绍了动作图像MVC3 Razor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 MVC3 中使用 Razor 用图像替换链接的最佳方法是什么.我现在只是这样做:

What is the best way to replace links with images using Razor in MVC3. I simply doing this at the moment:

<a href="@Url.Action("Edit", new { id=MyId })"><img src="../../Content/Images/Image.bmp", alt="Edit" /></a> 

有更好的方法吗?

推荐答案

您可以为 HtmlHelper 创建一个扩展方法来简化您的 CSHTML 文件中的代码.你可以用这样的方法替换你的标签:

You can create an extension method for HtmlHelper to simplify the code in your CSHTML file. You could replace your tags with a method like this:

// Sample usage in CSHTML
@Html.ActionImage("Edit", new { id = MyId }, "~/Content/Images/Image.bmp", "Edit")

这是上面代码的示例扩展方法:

Here is a sample extension method for the code above:

// 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);
}

这篇关于动作图像MVC3 Razor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆