3

I am creating extension methods for the HtmlHelper class in an MVC web app. Nothing is showing, not even the default InputExtensions.

public static class HtmlHelpers
{
    public static void RegisterScriptInclude(this HtmlHelper htmlhelper, string script)
    {
        if (!RegisteredScriptIncludes.ContainsValue(script))
        {
            RegisteredScriptIncludes.Add(RegisteredScriptIncludes.Count, script);
        }
    }

    public static string RenderScripts(this HtmlHelper htmlhelper)
    {
        var scripts = new StringBuilder();
        foreach (string script in RegisteredScriptIncludes.Values)
        {
            scripts.AppendLine("<script src='" + script + "' type='text/javascript'></script>");
        }
        return scripts.ToString();

    }

    private static SortedList<int, string> RegisteredScriptIncludes
    {
        get
        {
            SortedList<int, string> value = (SortedList<int, string>)HttpContext.Current.Items["RegisteredScriptIncludes"];
            if (value == null)
            {
                value = new SortedList<int, string>();
                HttpContext.Current.Items["RegisteredScriptIncludes"] = value;
            }
            return value;
        }
    }

}

The extension methods are not showing in the code either.

Where are they?

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
Paul Knopf
  • 9,568
  • 23
  • 77
  • 142

2 Answers2

9

Did you forget a using statement? Specifically you'd need "using path.to.my.namespace;" to get the extension methods in.

John Feminella
  • 303,634
  • 46
  • 339
  • 357
  • For me it's because I copied over a file from a different project and forgot to update the namespace. – Drew Feb 19 '19 at 18:42
3

Another obvious thing to check for, in case anyone finds this post, is forgetting the "this" keyword in the first argument of your extension method. If you forget that, there isn't much the compiler can do to help you!

Carl Niedner
  • 173
  • 2
  • 9