Banner Ad

Showing posts with label Razor. Show all posts
Showing posts with label Razor. Show all posts

Saturday, December 20, 2014

ASP.Net MVC – Create Custom HTML Helpers

By Francis   Posted at   11:52 AM   Razor No comments
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)
        {
            // Create a link with an image
            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>


The helper class is static, since it can be called in a easy manner also handy.
Happy coding!
Connect with Us