Custom Helpers In MVC

Introduction

In this article, we will see how to create Custom Helper in MVC. The custom helpers are very useful while developing projects.

Custom helpers are helpful in rapid developing and reusing of the code. We can add extension method to the existing html helper object with our custom code and that can be used across the project.

We have two types of custom helpers,

  • Inline Helpers
  • External Helpers

Inline Helpers

We can create inline helpers inside the view and that can be used within that view.

External Helpers

External Helpers can be used with the help ofthe extension method that this used. In  the Decorator pattern, we can extend the existing html helpers object with our custom extension method code and that can be used across the project.

Steps to create Custom Helper.

  1. Create MVC Project.

     MVC Project

     MVC Project

  2. Add Controller to the Controllers folder.

    Add Controller

  3. Create an array object with week items. We are going to use it in our View with Custom Helpers.

    code

  4. Create View with Empty View Model.

    Empty view model

  5. Here, we are creating the helper object RKCreateList in which we are creating un-ordered list to display our string Model.

  6. Call the Inline Helper.
    1. @* Calling External Helper *@  
    2. @Html.RKList(Model)  
    Inline helper

  7. Configure your Controller as default in RouteConfig file and execute the project.

    Configure

    Configure

Creating External Custom Helper

  1. Add Helpers folder to the project and add RKCustomHelper class.

    Helper folder

    Helper folder

  2. Create RKList helper object by extending the existing HtmlHelper class. Here, we have added our own custom code to generate the design. This helper class can be used across the project.

    code

  3. Include the project namespace and call the Custom Helper. Then, execute the project.
    1. @using MVCCustomHelper.Helpers  
    2.   
    3. @* Calling External Helper *@  
    4. @Html.RKList(Model) 
    code

    Helper folder
Hope this article helps you in understanding the Custom Helper concept in MVC. Please send your comments.