Search code examples
asp.netc#-4.0razorrazor-2asp.net-webpages

How to reference functions from other function files in ASP.NET Web Pages 2?


Here's the situation:

Let's say I have two files in App_Code containing blocks of functions in each:

Here's sample function #1 in file AppCode/File1.cshtml:

@functions {
  public static Boolean getTrue() {
    return true;
  }
}

Here's sample function #2 in file AppCode/File2.cshtml:

@functions {
  public static Boolean getFalse() {
    return false;
  }
}

I can reference the either functions in CSHTML files from my root folder via @File1.getTrue() or @File2.getFalse().

However, can I call @File2.getFalse() in AppCode/File1.cshtml so that:

@functions {
   public static Boolean getTrue() {
     return (!@File2.getFalse());
   }
}

Solution

  • Code in a function marked with the helper keyword is pure C#. Therefore you should remove the Razor @ sign. That should only be used to render server-side variables and expression results to the browser.

     @functions {
       public static Boolean getTrue() {
         return (!File2.getFalse());
       }
    }