22

I have the below function that I would like to be available to several .cshtml views in my asp.net web pages 2 application. How can I make this function available to any view in the application (as opposed to just one).

@functions {

    public bool DisplayButton(String startDate, String endDate)
    {
        return Convert.ToDateTime(startDate) < DateTime.Now && Convert.ToDateTime(endDate) > DateTime.Now;
    }
}
Robert
  • 1,638
  • 7
  • 34
  • 45

3 Answers3

26

Create a file called Functions.cshtml in App_Code and then paste the code you have into the file. Then you can call the DisplayButton method in any .cshtml file by prefixing it with the file name:

var myBool = Functions.DisplayButton(DateTime.Now, DateTime.Now.AddDays(30));

For more on working with functions and helpers in ASP.NET Web Pages, read this: http://www.mikesdotnetting.com/Article/173/The-Difference-Between-@Helpers-and-@Functions-In-WebMatrix

Mike Brind
  • 28,238
  • 6
  • 56
  • 88
  • I have this error message. CS0120: An object reference is required for the non-static field, method, or property 'Functions.AgoDateString()' – Georgi Kovachev Dec 01 '16 at 22:53
  • This works. As the linked article says the files Functions.cshtml may be called anything, but the methods declared must be public static, and they're called by referencing the file name @Functions.MyMethod(). If the methods are not public static you will receive a similar error to Georgi. Also note that MSVC autogenerates the required classes for you. – Anthony Aug 23 '17 at 11:57
2

You can define "global" helper functions in a Razor file in the AppCode directory as described here: http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx. However, helpers only render page elements; they cannot return a value (or more correctly, the returned value is the HTML markup to be rendered).

If you need to return a value, your best bet is an extension method.

Peter Gluck
  • 8,168
  • 1
  • 38
  • 37
  • 3
    The functions keyword is used to define a function (method) that returns a value defined by the method signature. The helper keyword defines a Razor template that renders HTML. – Mike Brind Jul 11 '13 at 20:28
1

Don't see why you couldn't have a static class with a static method and just include it at the top of every view and then use it

krilovich
  • 3,475
  • 1
  • 23
  • 33