Question

I'm building an ASP.Net MVC website. Rather than have everything in one project, I've decided to separate the Web, Model and Controller out into different projects in the same solution, that reference each-other.

The referencing goes like this:

Web ---[references]---> Controller ---[references]---> Model

Now I wanted to add 2 custom methods to the HtmlHelper class - they're called "IncludeScript" and "IncludeStyle". They each take a single string parameter, and generate a script or link tag respectively.

I've created an extender class, according to documentation on the web, and written the two methods and compiled the application.

Now, when I go into the Public.Master page (which is my main master-page, and one of the places where I intend to use these methods), I can enter code such as below:

<%= Html.IncludeScript("\js\jquery.js") %>

The IntelliSense picks up and IncludeScript method and shows me the syntax just fine. So I'd expect that everything should work.

But it doesn't.

Everything compiles, but as soon as I run the application, I get the following run-time error from line 14 of Default.aspx.cs:

c:\\Projects\\PhoneReel\\PhoneReel.Web\\Views\\Shared\\Public.Master(11): error CS0117: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'IncludeScript'

Here's the line of code that the error happens on:

httpHandler.ProcessRequest(HttpContext.Current);

Any ideas what could be going wrong here?

Was it helpful?

Solution

Check to make sure that the namespace of your extensions is accessible to our view. You need either this in your view:

<%@ Import Namespace="MyRootNamespace.NamespaceForMyHtmlHelperExtensions"%>

or this in your web config namespaces section:

<add namespace="MyRootNamespace.NamespaceForMyHtmlHelperExtensions"/>

OTHER TIPS

If you're using strongly typed views, and your extension method is extending HtmlHelper<object>, it's not going to find the extension. You'd have to create a generic extender to extend HtmlHelper<T>.

public static string IncludeScript<T>(this HtmlHelper<T> html, string url) {
   return "<script type=\"text/javascript\" src=\"" + url + "\"></script>";
}

Then you'll see your extender method show up.

I hope that helps.

Make sure to have an import directive to your extensions methods namespace in your page.

Otherwise, Visual Studio might be able to see but your website won't be able to.

Are you sure the compiler is set to .NET Framework 3.5? This happened to me when I inadvertently set the compiler to .NET Framework 2.0

In the IncludeScript method make sure that what you are extending is System.Web.Mvc.HtmlHelper. It's possible there is an HtmlHelper in some other namespace.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top