I have functions in my view that is shared by several pages:
@functions { public HtmlString ModeImage(ModeEnum mode) { switch(mode) { case AMode: new HtmlString("<img etc..."); break; // more etc... } } }
Is there a way to have it in a separate file and include it on each page without having to copy and paste it in to each one. I know I can write a .cs file and access it per page, but the function really concerns the view and I'de hate to have to recompile if this function changes.
You can add support for Pages to any ASP.NET Core MVC app by simply adding a Pages folder and adding Razor Pages files to this folder.
The Razor View Engine is a bit slower than the ASPX View Engine. Razor provides a new view engine with streamlined code for focused templating. Razor's syntax is very compact and improves readability of the markup and code. By default MVC supports ASPX (web forms) and Razor View Engine.
Razor is a templating engine and ASP.NET MVC has implemented a view engine which allows us to use Razor inside of an MVC application to produce HTML. However, Razor does not have any ties with ASP.NET MVC. Now, Razor Syntax is compact which minimizes the characters to be used, however it is also easy to learn.
cshtml files are razorpages or MVC views, they does not contain any C#-written client-side code. If you wan to do so, you must use JavaScript. However, a . razor file, also know as a Razor component, can have C# written in it and run on client's browser.
(Here's a more detailed version of the existing answers.)
Create a folder called App_Code
in the root of the MVC project if it doesn't already exist. In here, create an empty razor view and name it whatever you want:
Add @helper
s and/or static
methods to it as needed:
@helper ShowSomething() { <span>Something</span> } @functions { public static int CalculateSomething() { return 1; } }
Then use them from your views by first accessing the shared view by name:
@Shared.ShowSomething() @Shared.CalculateSomething()
This sounds like you want the Razor @helper methods described in the blog post ASP.NET MVC3 and the @helper syntax within Razor by Scott Guthrie.
Here is the overview... "The @helper syntax within Razor enables you to easily create re-usable helper methods that can encapsulate output functionality within your view templates. They enable better code reuse, and can also facilitate more readable code."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With