Adding Menu functionality in Html Helper class using Extension method in ASP.NET MVC

No.of Views1241
Bookmarked0 times
Downloads 
Votes0
By  Dhananjay Kumar   On  16 May 2010 05:05:13
Tag : ASP.NET , ASP.NET MVC
This article will show how to add new functionality in HtmlHelper class using Extension method. This will give step by step explanation of, how to create or add MENU functionality n Html helper class and then use that in view of ASP.Net MVC application.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Objective

This article will show how to add new functionality in HtmlHelper class using Extension method. This will give step by step explanation of, how to create or add MENU functionality n Html helper class and then use that in view of ASP.Net MVC application.

Step 1

Create an ASP.Net MVC application.
File->New->Project->web->ASP.Net MVC Application

 

Image Loading

Step 2

Create Extension method for Html Helper class.

a.    Add a class to the project. Give a significant name. I am giving name MenuExtension
b.    Convert this class to a static class.
c.    This class contains two methods.

        1.    Extension method Menu.
              a.    This is extension method to call HtmlHelper.
              b.    This is taking two parameters as input.
              c.    First parameter is class name for which this method is extension method. (Please see my article on Extension Method for complete detail)
              d.    Second parameter is items of type Object.

public static string Menu(this HtmlHelper helper, Object items)
        {
            return "<menu>" + MenuExtension.GetItems(items) + "</menu>";
        }


      2.    Static method GetItems
            a.    This is a static method to the class.
            b.    This is taking one input parameter
            c.    This is returning a list
            d.    This is building the list by encoding the items into a list of anchor tag.

public static string GetItems(Object items)
        {
            if (items == null)
            {
                throw new ArgumentNullException("items");
            }
            if (items is IEnumerable == false)
            {
                throw new InvalidCastException("Item must be IEnumerable");
            }

            var menuItems = (IEnumerable)items;
            var builder = new StringBuilder();
            foreach (Object o in menuItems)
            {
                builder.AppendFormat("<li><a href=#>{0}</a></li>", HttpUtility.HtmlEncode(o.ToString()));
            }
            return builder.ToString();
        }

So, the entire class will look like below listing.

MenuExtension.cs
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections;
using System.Text; 

namespace CustomMenu
{
    public static  class MenuExtension
    {
        public static string Menu(this HtmlHelper helper, Object items)
        {
            return "<menu>" + MenuExtension.GetItems(items) + "</menu>"; 
        }

        public static string GetItems(Object items)
        {
            if (items == null)
            {
                throw new ArgumentNullException("items");
            }
            if (items is IEnumerable == false)
            {
                throw new InvalidCastException("Item must be IEnumerable");
            }

            var menuItems = (IEnumerable)items;
            var builder = new StringBuilder();
            foreach (Object o in menuItems)
            {
                builder.AppendFormat("<li><a href=#>{0}</a></li>", HttpUtility.HtmlEncode(o.ToString()));
            }
            return builder.ToString();
        }

    }
}

Step 3


Create the Controller’s Action

It is a very simple action.  It is just creating list of strings and passing that to View. This action is inside controller Home.

public ActionResult Menu()
        {
            List<String> list = new List<String>();
            list.Add("File");
            list.Add("Edit");
            list.Add("Save");
            list.Add("Save As");
            list.Add("Exit");

            return View(list);
        }

Step 4

Create the View

a.    Right click on Edit action and select Add view
b.    Leave the default setting

 

Image Loading

c.    Now in Menu.aspx , import namespace of Extension Method

 

Image Loading

d.    Now , we could see with Html  class ,  .Net intellisense is able to sense the extension method
 

Image Loading

e.    Now add following code in Menu.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace="CustomMenu" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
	Menu
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Menu</h2>
    
    <%= Html.Menu(ViewData.Model) %>

</asp:Content>

Step 5

Adding link at the main page for file uploading

a.    Open site.master in Views->Shared Folder
b.    Add below line in menu tag

 

Image Loading

c.    So, the Menu element will look like

<div id="menucontainer">
            
                <ul id="menu">              
                    <li><%= Html.ActionLink("Home", "Index", "Home")%></li>
                      <li><%= Html.ActionLink("Menu", "Menu", "Home")%></li>
                    <li><%= Html.ActionLink("About", "About", "Home")%></li>
                </ul>
            
            </div>

  Step 6

Press F5 to run the application

 

Image Loading

Enjoy happy coding.

 
Sign Up to vote for this article
 
About Author
 
Dhananjay Kumar
Occupation-Software Engineer
Company-Infosys Technolgies,Pune
Member Type-Gold
Location-India
Joined date- 20 Jul 2009
Home Page-http://dhananjaykumar.net/
Blog Page-http://dhananjaykumar.net/
Dhananjay Kumar is Microsoft MVP on connected system. He blogs at http://dhananjaykumar.net/ . You can follow him http://twitter.com/debugmode_/ and reach him at dhananjay.25july@gmail.com
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top