Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
    }
}
like image 288
Robert Avatar asked Jul 11 '13 20:07

Robert


People also ask

What is the difference between Cshtml and Razor?

razor helps you embed serverside code like C# code into web pages. cshtml is just a file extension. razor view engine is used to convert razor pages(. cshtml) to html.

What can the @page directive do in a Razor page?

@page makes the file into an MVC action, which means that it handles requests directly, without going through a controller. @page must be the first Razor directive on a page. @page affects the behavior of other Razor constructs. Razor Pages file names have a .

What are Razor content pages?

Most Razor files are intended to be browsable and contain a mixture of client-side and server-side code, which, when processed, results in HTML being sent to the browser. These pages are usually referred to as "content pages".

Which type of content is observed on a Razor web page?

In a web page that uses the Razor syntax, there are two kinds of content: client content and server code. Client content is the stuff you're used to in web pages: HTML markup (elements), style information such as CSS, maybe some client script such as JavaScript, and plain text.


Video Answer


1 Answers

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

like image 102
Mike Brind Avatar answered Nov 02 '22 22:11

Mike Brind