Reputation: 3914
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" />
Upvotes: 3
Views: 575
Reputation:
Use MvchtmlString:
public static MvcHtmlString Image(this HtmlHelper helper, string id, string url, string alternateText)
{
// ...
return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing));
}
Upvotes: 1
Reputation: 4298
Instead of returning string try returning MvcHtmlString
,
public static MvcHtmlString Image(this HtmlHelper helper, string id, string url, string alternateText)
{
}
Upvotes: 1
Reputation: 24232
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));
}
Upvotes: 2