Problem creating my own extension to HtmlHelper

我只是一个虾纸丫 提交于 2019-12-10 19:23:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!