HTML Helpers are classes that helps to render HTML controls in Views. We can also create our own HTML Helpers. In this post, I’m going to explain how to create a simple Custom HTML Helper. The main purpose creating custom HTML helper is reuseability.
Step 1
Create a static class and add method to it like below.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace MVCTutorial
- {
- public static class CustomHTMLHelper
- {
- public static MvcHtmlString ImageLink(string action, string controller, string imgageURL)
- {
-
- return MvcHtmlString.Create(String.Format("<a href=\"{1}\\{0}\"> <img src=\"{2}\" /></a>", action, controller, imgageURL));
- }
- }
- }
Step 2
Access the custom helper class in a View.
- <!DOCTYPE html>
- <html>
- <head>
- <meta name = "viewport" content="width=device-width" />
- <title>Sample</title>
- </head>
- <body>
- <div>
- @CustomHTMLHelper.ImageLink("Home","Account","your image url")
- </div>
- </body>
- </html>