2013-09-25 120 views
3

我已经创建了下面的HTML帮助器类,用于显示图片:自定义助手工作不正常

类:

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") 

现在,当我在我的视图中使用自定义助手图像不显示,而不是图像以下消息打印在我们身上B页数

<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

为什么不ü通过图像的应用相对路径? –

+0

我不明白... –

+0

“〜/ Content/images/icons-18-black.png” –

回答

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)); 
} 
+0

为什么我们不应该使用mvcHtmlString? –

+0

我的评论是一个链接,点击它。它也可以工作,但将来它可能会被弃用,没有理由使用它而不是'HtmlString'。 – Stijn

1

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

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

} 
+0

[你不应该在MVC 3和更高版本中使用'MvcHtmlString'。](http://stackoverflow.com/a/3382908/247702) – Stijn

+0

这两个答案都正常工作。 –

1

使用MvchtmlString:

public static MvcHtmlString Image(this HtmlHelper helper, string id, string url, string alternateText) 
{ 
// ... 
    return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing)); 
}