VB.NET and MVC 5 using custom helpers with in-buil

2019-04-14 09:23发布

问题:

I'm working on an MVC 5 project using VB.NET and EF 6. I have added an EditorTemplates nuget package which relies upon Custom Global Helpers.

In C# I can merely add new helpers wherever as a public static class, then add the namespace to ~/Views/Web.config and off I go. To the best of my knowledge C# and VB.NET differ here greatly.

After much battling with the compiler and Stack Overflow searching I found that I could get the custom helpers to work in views if placed them in the App_Code folder.

I used a Module with the <System.Runtime.CompilerServices.Extension> attribute applied to each method. Then added to ~/Views/Web.config and the App_code folder and compile.

Imports System.Web.Mvc
Public Module HtmlHelpers
    <System.Runtime.CompilerServices.Extension>
    Public Function HelperName(ByVal helper As HtmlHelper, hn As HelperName) As MvcHtmlString        
        Return MvcHtmlString.Create(hn.ToString())
    End Function
End Module

This allows me to use the new custom helpers, but completely blocks out all of the in-built html helpers like DisplayFor, EditorFor and ActionLink.

Please correct me if I'm wrong. There seems to be no documentation whatsoever about this online, apart from confirming the issue, then ignoring it for over 5 years.

How can I use both? I'm at the end of my tether and losing faith in Microsoft's support/documentation.

回答1:

Solution:

  1. Do not use App_Code. Put the helpers elsewhere. I've put mine in ~/Helpers/
  2. Do not use namespaces. This was probably my downfall, though cannot be sure without further testing.
  3. Add root project namespace to ~/Views/Web.config

    <add namespace="MyProjectName" />
    

    NOT

    <add namespace="MyProjectName.Helpers" />
    <add namespace="HtmlHelpers" />
    <add namespace="OrAnythingLikeThis" />
    
  4. Ensure helpers are being compiled at build time (Class.vb > Properties > Build Action: Compile)

I'm 99% sure that's it. I had issues with BootstrapEditorTemplates as they were C# and I'm working in VB.NET. To solve this I converted the helpers to VB.NET and placed them all in a single HtmlHelpers.vb file, in ~/Helpers/, with the rest of my custom ones. Doing this probably wasn't all necessary; you could probably accomplish the same by just removing the namespace in the C# helper files, but I haven't tested.

If this doesn't work then give me a shout (on this question, not pm) and I'll come back and try to solve it.