Asp.net implements the method of using the Razor template engine in non-MVC, mvcrazor
This example describes how to use the Razor template engine in non-MVC mode. Share it with you for your reference. The specific analysis is as follows:
Template engine Introduction
Razor, Nvelocity, Vtemplate, and Razor are generally used in MVC projects. Here we describe the usage in non-MVC projects.
How to Use Razor template engine in non-MVC
With the open-source RazorEngine, we can use the Razor engine in non-asp.net mvc projects, and even use Razor in the console and WinForm projects (develop code generators by yourself)
How to Use Razor
Environment setup:
① Add reference RazorEngine. dll
② Create cshtml
Create an html file and change it to cshtml. Note: After you add the -- html page and change it to the cshtml method, there is an automatic prompt. You must turn off the file and open it again. We recommend that you add the -- new item -- html page and directly change it to cshtml to create the cshtml file, which can be used for automatic prompts.
Start to use:
1. Use Razor syntax in cshtml
In Razor, @ is followed by an expression indicating that the expression value is output at this position. The Model in the template is the object passed to the template.
C # code in}, and C # code can also be mixed with html code
<!DOCTYPE html>
2. Use Razor in a general processing program:
The Razor object uses the Parse method to Parse the read cshtml into an assembly and then generate html.
Public void ProcessRequest (HttpContext context) {context. Response. ContentType = "text/html"; string fullPath = context. Server. MapPath (@"~ /Razordemo/Razor1.cshtml "); // obtain the cshtml File path string cshtml = File. readAllText (fullPath); // obtain the file content string html = Razor. parse (cshtml); // Parse the cshtml file to get the html context. response. write (html );}
3. How to read object values in cshtml files
Another overload of the Razor. Parse () method is to upload a Model object. In the cshtml file, the attributes of the object can be clicked through the Model.
Parsing in a general handler:
Dog dog = new Dog();dog.Id = 100;dog.Height = 120;string html = Razor.Parse(cshtml, dog);context.Response.Write(html);
Read object attributes in cshtml:
<! DOCTYPE html>
I hope this article will help you design your asp.net program.