Using a Razor @functions in several webpages (.cshtml files)

Robert picture Robert · Jul 11, 2013 · Viewed 15k times · Source

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;
    }
}

Answer

Mike Brind picture Mike Brind · Jul 11, 2013

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