本文主要是介绍MVC5创建自定义图片链接,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在项目中新建Helper文件夹,添加类:ImageHelpers.cs。截图如下:
ImageHelpers.cs代码如下:
using System.Web.Mvc;
using System.Web.Routing;namespace PDMPAPP.Helper
{public static class ImageHelpers{public static MvcHtmlString ImageLink(this HtmlHelper helper, string actionName, string imageUrl, string alternateText, object routeValues, object linkHtmlAttributes, object imageHtmlAttributes){var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);var url = urlHelper.Action(actionName, routeValues);//建立链接 var linkTagBuilder = new TagBuilder("a");linkTagBuilder.MergeAttribute("href", url);linkTagBuilder.MergeAttributes(new RouteValueDictionary(linkHtmlAttributes));//建立图片var imageTagBuilder = new TagBuilder("img");imageTagBuilder.MergeAttribute("src", urlHelper.Content(imageUrl));imageTagBuilder.MergeAttribute("alt", alternateText);imageTagBuilder.MergeAttribute("alt", alternateText);imageTagBuilder.MergeAttributes(new RouteValueDictionary(imageHtmlAttributes));//将图片加至链接中linkTagBuilder.InnerHtml = imageTagBuilder.ToString(TagRenderMode.SelfClosing);return MvcHtmlString.Create(linkTagBuilder.ToString());}//调用方法://1.在调用图片链接扩展方法页面最上面添加引用:@using PDMPAPP.Helper;//2.使用方法形如:@Html.ImageLink("Edit", Url.Content("~/media/image/1.jpg"), "alt", new { id = item.M_Id }, new { @class = "btn"},new { style = "border:0" })}
}
调用方法参考类中注释
这篇关于MVC5创建自定义图片链接的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!