Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prove me wrong: VB.NET HtmlHelper Extension Method NOT Working in MVC 4 with VS 2012

No matter how many times I try, I cannot get my HTML Helper extension method to work. Here's the test steps I've created, if someone wants to try it out themselves:

  1. Using Visual Studio 2012, I create a new "Visual Basic ASP.NET MVC 4 Internet Web Application" using the "Internet Application" project template.

  2. I create a folder "~/Views/Helpers"

  3. I create a file "DisplayForPropertyHelper.vb" and add the following code:

    Namespace TestProject.Extensions
        Public Module HtmlHelperExtensions
            <Extension()>
            Public Function DisplayForProperty(helper As HtmlHelper) As MvcHtmlString
                Return MvcHtmlString.Create("TEST")
            End Function
        End Module
    End Namespace
    
  4. I open up "~/Views/Web.config" and change the following (I add the extensions namespace):

    <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.Optimization"/>
            <add namespace="System.Web.Routing" />
            <add namespace="TestProject.Extensions"/>
          </namespaces>
        </pages>
    </system.web.webPages.razor>
    
  5. Compile the project

  6. Choose ANY razor view file, and type @Html.Display-and you will see that the extension method does not show up.

  7. Add to the razor view file @Imports TestProject.Extensions then save and close the file.

  8. Reopen file, and type @Html.Display-and you will see that the extension method does not show up.

  9. You can even try closing VS2012 and reopening the project. Won't make a difference.

I have been battling with this for weeks now. All answers I've found on here and elsewhere are NO help. Someone must have an answer.

like image 842
emkayultra Avatar asked Feb 06 '13 06:02

emkayultra


1 Answers

Make sure that you prefixed your namespace with your application name. So for example if the application you created was called MvcApplication1 in your ~/Views/web.config you should put:

<add namespace="MvcApplication1.TestProject.Extensions"/>

and not just:

<add namespace="TestProject.Extensions"/>

Yeah, I guess, it's one of those VB.NET thingies :-) Oh and don't forget to close and open the Razor view after making changes to the ~/Views/web.config file, otherwise your changes won't be taken into account immediately (if you run the application it will work of course).

like image 128
Darin Dimitrov Avatar answered Sep 28 '22 02:09

Darin Dimitrov