我创建了以下用于显示图像的Html Helper类:
类别:
namespace MvcWebMobile.CustomHelpers
{
public static class CustomHelper
{
public static string Image(this HtmlHelper helper, string id, string url, string alternateText)
{
return Image(helper, id, url, alternateText, null);
}
public static string Image(this HtmlHelper helper, string id, string url, string alternateText, object htmlAttributes)
{
// Create tag builder
var builder = new TagBuilder("img");
// Create valid id
builder.GenerateId(id);
// Add attributes
builder.MergeAttribute("src", url);
builder.MergeAttribute("alt", alternateText);
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
// Render tag
return builder.ToString(TagRenderMode.SelfClosing);
}
}
}
查看:
@Html.Image("img1", "../../Content/images/icons-18-black.png", "logo")
现在,当我在视图中使用自定义帮助程序时,不显示图像,而不是在网页上打印图像跟随消息
<img alt="logo" id="img1" src="../../Content/images/icons-18-black.png" /> <img alt="logo" border="4px" id="img1" src="../../Content/images/icons-18-black.png" />
答案 0 :(得分:2)
您的帮助者应该返回HtmlString
而不是string
。
public static HtmlString Image(this HtmlHelper helper, string id, string url, string alternateText)
{
return Image(helper, id, url, alternateText, null);
}
public static HtmlString Image(this HtmlHelper helper, string id, string url, string alternateText, object htmlAttributes)
{
// ...
return new HtmlString(builder.ToString(TagRenderMode.SelfClosing));
}
答案 1 :(得分:1)
而不是返回字符串尝试返回MvcHtmlString
,
public static MvcHtmlString Image(this HtmlHelper helper, string id, string url, string alternateText)
{
}
答案 2 :(得分:1)
使用MvchtmlString:
public static MvcHtmlString Image(this HtmlHelper helper, string id, string url, string alternateText)
{
// ...
return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing));
}