Asp.net mvc 自定义帮助程序工作不正常
我创建了以下用于显示图像的Html帮助器类: 类别:Asp.net mvc 自定义帮助程序工作不正常,asp.net-mvc,asp.net-mvc-4,razor,Asp.net Mvc,Asp.net Mvc 4,Razor,我创建了以下用于显示图像的Html帮助器类: 类别: namespace MvcWebMobile.CustomHelpers { public static class CustomHelper { public static string Image(this HtmlHelper helper, string id, string url, string alternateText) { return Image(he
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")
查看:
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" />
您的助手应该返回
HtmlString
而不是字符串
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));
}
尝试返回MvcHtmlString
,而不是返回字符串
public static MvcHtmlString Image(this HtmlHelper helper, string id, string url, string alternateText)
{
}
使用MvchtmlString:
public static MvcHtmlString Image(this HtmlHelper helper, string id, string url, string alternateText)
{
// ...
return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing));
}
为什么不传递应用程序图像的相对路径?我不明白…~/Content/images/icons-18-black.png“我试过了,但它不起作用。为什么我们不应该使用mvcHtmlString?我的评论是一个链接,单击它。它也可以工作,但将来可能会被弃用,没有理由使用它来代替HtmlString
。