Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an extension method in C#

I'm trying to create an extension method in C# for the HtmlHelper class. I've read the MSDN page for it, and I'm sure I'm referencing the correct namespaces. I wonder what I could be doing wrong.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; //Correctly referencing the necessary namespaces, right?

namespace MvcApplication1.HelperMethods
{
    public static class NavigationalMenu
    {
        public static string MyMenu(this HtmlHelper helper)
        {
            CategoryRepository categoryRepo = new CategoryRepository();
            var categories = categoryRepo.FindAllCategories();

            foreach (Category c in categories)
            {
                helper.RouteLink(blablabla); //Construct links and return them.
            }

            //helper.RouteLink doesn't show up! C# wipeouuuuuttttt.
            //It's as if 'helper' doesn't have the RouteLink method there.
        }
    }
}

First time that this happens to me when programming in C#. Anyone else encounter this problem?


1 Answers

According to MSDN:

Extensions to the HtmlHelper class are located in the System.Web.Mvc.Html namespace. These extensions add helper methods for creating forms, rendering HTML controls, rendering partial views, input validation, and more.

Trying including the System.Web.Mvc.Html namespace. LinkExtensions.RouteLink gives its namespace as that (it says it's in System.Web.Mvc.dll, just in a different namespace).

like image 197
Jonathon Bolster Avatar answered Mar 14 '26 03:03

Jonathon Bolster