App_Code required for ASP.NET MVC 4 HtmlHelper Extension in VB.NET?

I spent most of two hours trying to figure it out. Here:

I just want to create an HTMLHelper extension method. This has been done many times before, and I know that I code it correctly. However, Razor seems to know about this if I put the code file in App_Code (the folder that I thought no longer makes sense in the MVC world!)

How do I know this?

Quite simply ... I have two identically encoded HTMLHelper extension methods in two separate files with the same name.

The first file, located inside ~ / Extensions, contains the DisplayForProperty extension method

The second file, placed inside ~ / App_Code, contains the DisplayForProperty2 extension method

When in the view I type @Html.Displ - Intellisense shows me DisplayForProperty2 !

I do not have @using instructions, as this does not seem necessary to view DisplayForProperty2 . Not to mention that in this case, nothing will change.

So why is this? Should this be so? Is it just that the Razor is delayed, or am I alone retarded?

I am using a completely updated copy of VS 2012.

PS. On the other hand, do I need to place a link to namespaces in each web.config file under each / directory submission (as well as in each separate Area) plus in the root? Why can't I just put this in the root directory or in the root / Views directory?

+4
source share
4 answers

You do not need to place html helper extension methods inside App_Code. While a bit old, the asp.net manual: http://www.asp.net/mvc/tutorials/older-versions/views/creating-custom-html-helpers-cs helps you very well.

Usually I have a Helpers folder in the root of the MVC project with separate class files for each. They are in the Project.MVC.Helpers namespace, and I add @using Project.MVC.Helpers in the Razor views in which I want to use the helper.

+2
source

The app_code folder is still a special folder that automatically compiles and references the project.

0
source

Did you check the namespace that was generated in the HtmlHelper class when you put it in a folder outside of App_Code?

Perhaps all you are missing is the @using directive pointing to this namespace inside your view.

0
source

You may need to add the namespace that your assistant contains to the Web.config file inside your views folder.

  <system.web.webPages.razor> <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <pages pageBaseType="System.Web.Mvc.WebViewPage"> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="Namespace.Of.Your.Helper" /> </namespaces> </pages> </system.web.webPages.razor> 

This will allow your views to be used by your helper without @using, which refers to a namespace.

0
source

All Articles