gfrizzle
gfrizzle

Reputation: 12609

Extending HtmlHelper in .NET 4.0 MVC3 ASPX

I have code that works in a .NET 3.5 app that isn't working when I set it up the same way in .NET 4.0. The problem comes when I try to extend HtmlHelper. In .NET 4.0 MVC3, if I have a page that looks like this:

<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage(Of IEnumerable (Of MvcApplication2.MyModel))" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <%=Html.MyTest%>
</asp:Content>

and an extension like this:

Imports System.Runtime.CompilerServices

Module Extensions

    <Extension()>
    Public Function MyTest(htmlhelper As System.Web.Mvc.HtmlHelper) As String
        Return Now.ToLongTimeString
    End Function

End Module

it won't compile, because "Html" is not of type System.Web.Mvc.HtmlHelper like it was in the past, it's now of type System.Web.Mvc.HtmlHelper(Of IEnumerable (Of MvcApplication2.MyModel)). The error message on <%=Html.MyTest%> is:

'MyTest' is not a member of 'System.Web.Mvc.HtmlHelper(Of System.Collections.Generic.IEnumerable(Of MvcApplication2.MyModel))'.

How would I extend HtmlHelper in this configuration? Am I missing something in my setup that's causing "Html" to be of a different type than it was in the past? I haven't found anything online about a change in behavior, which leads me to believe that I've done something wrong somewhere.

UPDATE:

In reference to HtmlHelper(Of TModel) inheriting from HtmlHelper, why won't this code work?

Partial Public Class HtmlHelper

    Public Function MyOtherTest() As String
        Return Now.ToLongTimeString
    End Function

End Class

Referencing <%=Html.MyOtherTest%> produces the same error message.

Upvotes: 2

Views: 709

Answers (1)

SLaks
SLaks

Reputation: 887453

Views with typed models get typed HTML helpers so that helper methods can use the model type.
However, HtmlHelper(Of TModel) inherits HtmlHelper, so your code will work fine.

It's possible that you've added a reference to System.Web.WebPages.dll, so that the extension method is extending System.Web.WebPages.HtmlHelper, which is a different class.

Upvotes: 3

Related Questions