3

我创建了以下用于显示图像的 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" /> 
4

3 回答 3

2

您的助手应该返回 aHtmlString而不是 a 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));
}
于 2013-09-25T11:15:47.483 回答
1

而不是返回字符串尝试返回MvcHtmlString

 public static MvcHtmlString Image(this HtmlHelper helper, string id, string url, string alternateText)
 {

 }
于 2013-09-25T11:18:05.793 回答
1

使用 MvchtmlString:

public static MvcHtmlString Image(this HtmlHelper helper, string id, string url, string alternateText)
 {
// ...
    return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing));
 }
于 2013-10-15T09:14:55.717 回答