Custom Html Helpers in MVC
- Create a static method in a static class.
- The First parameter has to be the type to which we can add the extension method.
- The Return type should be IHtmlString, that are excluded from html encoding.
- To help in the creation of the HTML tags, use the Tab Builder class.
- Include the namespace of the Helper method in either the view or the web.config
-
namespace MVCCustomeHtmlHelper
{
public static class CustomHtmlHelpers
{
public static IHtmlString Image(this HtmlHelper helper, string src, string alt)
{
TagBuilder tagBuilder = new TagBuilder(“img”);
tagBuilder.Attributes.add(“src”, VartualPathUtility.ToAbsolute(src));
tagBuilder.Attributes.add(“alt”,alt);
return new
MvcHtmlString(tagBuilder.ToString(TagRenderMode.SelfClosing));
}
}
}
-
<img src=”@Url.Content(@Model.Photo)” alt=”@Model.AlternateText” /> or
@Html.Image(Model.Photo, Model.AlternateText)
-
<system.web.webPages.razor>
<pages pageBaseType=”System.Web.Mvc.WebViewPage”>
<namespaces>
<add namespace=” MVCCustomeHtmlHelper” />
</namespaces>
</pages>
</ system.web.webPages.razor>