.NET MVC3 Razor (VB!) Extensions not imported in v

2019-07-17 16:31发布

My extensions are not imported in my vbhtml view. I seem to be missing something somewhere.. Can anybody help please?

The module.vb:

Imports System.Runtime.CompilerServices

Namespace Areas.Admin.Models.Extensions
<Extension()> _
Public Module InputExtensions
    Public Function SelectHumanGroup(ByVal helper As HtmlHelper, ByVal name As String, Optional ByVal selectedValue As String = "", Optional ByVal htmlAttributes As Object = Nothing) As MvcHtmlString
        Return helper.DropDownList(name, repo.GetGroups(), htmlAttributes)
    End Function
End Module
End Namespace

The view.vbhtml:

@Imports MySite.Areas.Admin.Models.Extensions
@ModelType MySite.Models.MyViewModel

@Code
    ViewData("Title") = "Index"
End Code

<h2>Index</h2>


@Html.SelectHumanGroup("test")

3条回答
女痞
2楼-- · 2019-07-17 16:52

Your module.vb NEED to be in App_Code directory and namespaces should be declared as it was answered above.

查看更多
狗以群分
3楼-- · 2019-07-17 16:55

I'm a C# guy, but this should be valid for VB as well. It is better though that you add your extensions via Web.config instead. That way you don't have to add them in every view. Under your Views folder you find a Web.Config. Search for and add:

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.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="MySite.Areas.Admin.Models.Extensions" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>
查看更多
Juvenile、少年°
4楼-- · 2019-07-17 16:56

I think you need to decorate the Function and not the Model. I have something similar and it's working for me, check this out:

Imports System.Runtime.CompilerServices

Namespace Areas.Admin.Models.Extensions
Public Module InputExtensions
    <Extension()> _
    Public Function SelectHumanGroup(ByVal helper As HtmlHelper, ByVal name As String, Optional ByVal selectedValue As String = "", Optional ByVal htmlAttributes As Object = Nothing) As MvcHtmlString
        Return helper.DropDownList(name, repo.GetGroups(), htmlAttributes)
    End Function
End Module
End Namespace
查看更多
登录 后发表回答