Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

c# - Why is Extension Method Not Found in MVC4 Razor View?

Given the following string extension method

namespace JHS.ExtensionMethods
{
  public static class StringExtensions
  {
    public static string ToUSAPhone(this String str)
    {
      return String.Format("{0:(###) ###-####}", Double.Parse(str));
    }
  }
}

A @using statement was added to the MVC4 Razor view

@using JHS.ExtensionMethods;

and the following string value calls the extension method

@Model.producer.phone.ToUSAPhone()

which results in the following error

'string' does not contain a definition for 'ToUSAPhone'

I also tried putting the namespace in the web.config of the /Views folder and receive the same error.

<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.Optimization"/>
    <add namespace="System.Web.Routing" />
    <add namespace="JHS.ExtensionMethods"/>
  </namespaces>
</pages>

I have verified the extension method works by putting the same call in a C# class

string test=producer.phone.ToUSAPhone();

It seems the reference to the extension method is not available in the MVC4 Razor view but I can't figure out why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This happens if the type you are trying to use the extension method on is actually a dynamic. Check to see if the exception is being generated by the CSharp RuntimeBinder. If so, you can either use the method as a common or garden static method:

@StringExtensions.ToUSAPhone(Model.producer.phone)

Or you can cast the value to a string:

@(((string)Model.producer.phone).ToUSAPhone())

According to Eric Lippert (formerly of MSFT):

The reason behind the fact that dynamics do not support extension types is because in regular, non-dynamic code extension methods work by doing a full search of all the classes known to the compiler for a static class that has an extension method that match. The search goes in order based on the namespace nesting and available "using" directives in each namespace.

That means that in order to get a dynamic extension method invocation resolved correctly, somehow the DLR has to know at runtime what all the namespace nestings and "using" directives were in your source code. There is no mechanism handy for encoding all that information into the call site.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...