using System;using System.Web.Mvc;using System.Web.Routing; namespace MvcTest2.Helpers{ public static class ImageHelpers { public static MvcHtmlString ...
using System;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcTest2.Helpers
{
public static class ImageHelpers
{
public static MvcHtmlString ImgLink(this HtmlHelper helper,string actionName,string imgUrl,string alternateText,object routeValues,object linkHtmlAttributes,object imgHtmlAttributes)
{
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);//在哪一個頁面引用的就獲取這個頁面的url幫助實體類
var url = urlHelper.Action(actionName,routeValues);
var linkTagBuilder = new TagBuilder("a");//使用這個方法生成標簽
linkTagBuilder.MergeAttribute("href",url);
linkTagBuilder.MergeAttributes(new RouteValueDictionary(linkHtmlAttributes));
var imgTagBuilder = new TagBuilder("img");
imgTagBuilder.MergeAttribute("src",imgUrl);
imgTagBuilder.MergeAttribute("alt", alternateText);
imgTagBuilder.MergeAttribute("title", alternateText);
imgTagBuilder.MergeAttributes(new RouteValueDictionary(imgHtmlAttributes));
linkTagBuilder.InnerHtml = imgTagBuilder.ToString(TagRenderMode.SelfClosing);//轉換成自身標記結束的標簽
return MvcHtmlString.Create(linkTagBuilder.ToString());
}
}
方法返回一個linkImg
自定義Html輔助方法需要寫到靜態類靜態方法裡面