Topic: HTML Helper Extensions
Share/Save/Bookmark
Description: This code will show you how to add an Html Helper method to your MVC project by using extensions.



Under your MVC app, create a folder called "ViewHelpers"

Within that folder, create a class called anything you want to put your extension methods into.  (e.g. "MyExtensions")

Once you have that class created, add extension methods that you would use within your Views.

Below is an example of a class that takes in the HtmlHelper object and returns a string.

    public static class MyHelper
    {
        public static string MyMethod(this HtmlHelper helper)
        {
            
            // Getting an object out of Session

MyObject
 myObject = (MyObject)helper.ViewContext.HttpContext.Session["SomeNameInSession"];                          StringBuilder sb = new StringBuilder("Item Count: ");             sb.AppendFormat("{0} {1}", myObject.NumberOfItems(), "Item");             if (cart.NumberOfItems() != 1)             {                sb.AppendFormat("s");             }             return sb.ToString();         }     }

To use this Extension method in a View, Control, or MasterPage, you would use the code as follows:
     
<%=Html.MyMethod() %>


Note: Either use the default Namespace for your extention class of your entire site, or make sure the you
add the Namespace to the View, Control, or MasterPage that you are calling the method
from. 



Example of adding the Namespace reference:










<%@ Import Namespace="mySite.ViewHelpers" %>