3

I have created the following Html Helper Class for displaying a Image:

Class:

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

View:

@Html.Image("img1", "../../Content/images/icons-18-black.png", "logo")

Now when i use the custom helper in my view the Image is not displayed, instead of image following message is printed on web page

<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" /> 
Bob.
  • 3,894
  • 4
  • 44
  • 76
Bhupendra Shukla
  • 3,814
  • 6
  • 39
  • 62

3 Answers3

2

Your helper should return a HtmlString instead of 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));
}
user247702
  • 23,641
  • 15
  • 110
  • 157
1

Instead of returning string try returning MvcHtmlString,

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

 }
Jatin patil
  • 4,252
  • 1
  • 18
  • 27
1

Use MvchtmlString:

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