我已经制作了这个自定义的Html Helper:
public static MvcHtmlString Image(this HtmlHelper _helper, string _url, string _altText, object _htmlAttributes)
{
TagBuilder builder = new TagBuilder("image");
var path = _url.Split('?');
string pathExtra = "";
if (path.Length > 1)
{
pathExtra += "?" + path[1];
}
builder.Attributes.Add("src", VirtualPathUtility.ToAbsolute(path[0]) + pathExtra);
builder.Attributes.Add("alt", _altText);
builder.MergeAttributes(new RouteValueDictionary(_htmlAttributes));
return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
}
我工作得很精致。我必须说实话,这不是我的工作,但我在浏览stackoverflow的帮助时找到了它。
话虽如此,我想知道有没有办法改变这个方法,以便它既可以加载图像又可以作为超链接,可点击的图像?
答案 0 :(得分:2)
试试这个.. 您只需将图像包装到锚标记中即可。 请使用MergeAttribute方法添加适当的href值,就像对图像一样。
public static MvcHtmlString Image(this HtmlHelper _helper, string _url, string _altText, object _htmlAttributes)
{
TagBuilder builder = new TagBuilder("image");
TagBuilder anchorabBuilder = new TagBuilder("a");
var path = _url.Split('?');
string pathExtra = "";
if (path.Length > 1)
{
pathExtra += "?" + path[1];
}
builder.Attributes.Add("src", VirtualPathUtility.ToAbsolute(path[0]) + pathExtra);
builder.Attributes.Add("alt", _altText);
builder.MergeAttributes(new RouteValueDictionary(_htmlAttributes));
anchorabBuilder.InnerHtml = builder.ToString(TagRenderMode.SelfClosing);
return MvcHtmlString.Create(anchorabBuilder.ToString(TagRenderMode.Normal));
}