Razor HtmlHelper Extensions (or other namespaces f

2019-01-02 20:01发布

Dunno if this was happening in the PR or Beta, but if I create an extension method on HtmlHelper, it is not recognized in a Razor powered page:

namespace SomeNamespace.Extensions {
    public static class HtmlExtensions {
        public static string Foo(this HtmlHelper html) {
            return "Foo";
        }
    }
}

I added it to the <Namespaces> section in Web.config:

<pages>
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <!-- snip -->
    <add namespace="SomeNamespace.Extensions"/>
  </namespaces>
</pages>

But it throws a compile error when trying to view the page:

@Html.Foo()

If I recreate the page with WebForms it works fine. What's the deal?

Workaround

If I include @using SomeNamespace.Extensions in my Razor view, then it works, but I'd much rather just have it in Web.config

8条回答
不再属于我。
2楼-- · 2019-01-02 20:44

I had this same error in an MVC 4 application using Razor. In an attempt to clean up the web.config files, I removed the two webpages: configuration values:

<appSettings>
  <add key="webpages:Version" value="2.0.0.0" />
  <add key="webpages:Enabled" value="false" />

Once I restored these configuration values, the pages would compile correctly and the errors regarding the .Partial() extension method disappeared.

查看更多
有味是清欢
3楼-- · 2019-01-02 20:50

I had this issue in VS 2015. The following solved it for me:

Find "webpages:Version" in the appsettings and update it to version 3.0.0.0. My web.config had

<add key="webpages:Version" value="2.0.0.0" />

and I updated it to

<add key="webpages:Version" value="3.0.0.0" />
查看更多
登录 后发表回答