Can't create HtmlHelper methods in VB MVC app

2020-03-31 02:31发布

问题:

I can't figure out what I'm missing in the following code. I've got a method that should add a (dummy) helper extension:

Imports System.Runtime.CompilerServices

Namespace HtmlHelpers

    Public Module HelpExtensions

        <Extension()> _
        Public Function HelpMe(ByVal HtmlHelper As HtmlHelper) As String
            Return "<a>HELP</a>"
        End Function

    End Module

End Namespace

My view looks like this:

<%@ Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<%@ Import Namespace="HtmlHelpers" %>
<asp:Content ID="indexContent" ContentPlaceHolderID="body" runat="server">
    <%=Html.HelpMe()%>
</asp:Content>

But this gives me the following error:

'HelpMe' is not a member of 'System.Web.Mvc.HtmlHelper'.

What am I doing wrong?

回答1:

Not sure why the Import Namespace directive wasn't doing the trick, but I added

<add namespace="MyProject.HtmlHelpers"/>

to the <namespaces> section of web.config and it's working now. Maybe if I had done

<%@ Import Namespace="MyProject.HtmlHelpers" %>

it would have worked as well?



回答2:

Have you tried rebuilding your solution before attempting to use the extension method? I've had to do that with VB.NET in order for the compiler to pick up the existence of my extension methods.



回答3:

I guess I just found the solution.

Your helper's modules NEED TO BE in the App_Code directory.



回答4:

As gfrizzle said, adding the namespace reference to the web.config in the Views folder allows the page to display properly. However, I had to restart the client to get the Intellisense to work properly. I also had to explicitly add Import statements for namespaces that were already globally imported to the file with the extension module.

For example, when extending System.Web.Mvc.HtmlHelper I had to add the line

Imports System.Web.Mvc

in order for the page to display without error, despite the fact that the application compiles correctly and the namespace is checked on the project references tab.



回答5:

The problem could be that you have installed both MVC2 and MVC3. If so, when you write an HTMLHelper Custom with VB.NET Visual Studio throw ad Error "YourClass" is not a member of 'System.Web.Mvc.HtmlHelper'.

But if you run the page it works fine.

This is the solution: http://forums.asp.net/t/1694828.aspx/1

Solution 1) Upgrade your project to MVC3 Solution 2) Uninstall MVC3 Solution 3) Change .NET framework to 3.5 instead of 4.0 (disable MVC3) Solution 4) Write code in C# and you won't have any problem

Marco