Why is Extension Method Not Found in MVC4 Razor View?

后端 未结 4 1537
鱼传尺愫
鱼传尺愫 2020-12-20 11:20

Given the following string extension method

namespace JHS.ExtensionMethods
{
  public static class StringExtensions
  {
    public static string ToUSAPhone(         


        
相关标签:
4条回答
  • 2020-12-20 11:37

    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.

    0 讨论(0)
  • 2020-12-20 11:41

    There may be yet another trivial reason for this and it happened to me.

    The file that I created my extension in had "Content" as value for Build Action property on VS file properties pane.

    Switching it to "Compile" immediately fixed the issue, naturally...

    0 讨论(0)
  • 2020-12-20 11:44

    Build your project before adding your custom namespace for the extentions to your View.

    0 讨论(0)
  • 2020-12-20 11:55

    It's not just if the type you're calling the extension method on is dynamic, but if anything in the expression is dynamic and not cast.

    eg this is clearly dynamic:

    @ViewBag.ToJSON()
    

    But I first thought Mike's answer did not apply to me because I was doing this :

    @(ViewBag.UserProfile.GetJSONProfile().ToJSON())
    

    where ToJSON() is my extension method and GetJSONProfile() just returns object.

    I was just spacing out and being stupid but wanted to mention this.

    0 讨论(0)
提交回复
热议问题