问题
I have an extension method to HtmlHelper:
<%= Html.MyMethod( params )%>
It works in visual studio, but throws (at runtime):
Compiler Error Message: CS0117: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'MyMethod'
The odd bit is that this does work:
<%= HtmlHelperExtensions.MyMethod( Html, params ) %>
Why does my method not work as an extension, but does as a normal static call?
回答1:
I found the answer in the web.config - there's a section that tells it how to compile C# embedded in HTML:
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp"
extension=".cs"
type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
</compiler>
</compilers>
</system.codedom>
This is missing an extra flag that tells it to use the 3.5 compiler tricks that let extension methods and anonymous types work in the HTML:
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp"
extension=".cs"
type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5" />
</compiler>
</compilers>
</system.codedom>
回答2:
Make sure you are importing the namespace containing the extension method in your view.
<%@ Import Namespace="MyProject.MyExtensions"%>
Or add it in your web.config so it will be available on every view:
<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="MyProject.MyExtensions"/>
</namespaces>
来源:https://stackoverflow.com/questions/944015/problem-creating-my-own-extension-to-htmlhelper