The template engine introduces Razor, nvelocity, and vtemplate because Razor has automatic hints in VS and is easy to use and efficient.
Using the Razor template engine in non-MVC
With open source Razorengine, we can use the razor engine in non-ASP. NET MVC projects, and even use razor in the console, WinForm projects (develop code generators yourself)
How to use Razor environment build: 1, add Reference RazorEngine.dll 2, create cshtml
Create a new HTML and change the name to cshtml. Note: By adding the--html page and changing it to cshtml, you have the automatic prompt, you must turn off the file and reopen it. Recommended, add-new Item--html page is changed directly here to cshtml create cshtml file, directly available automatically prompt.
Specific usage: 1, using razor syntax in cshtml
Razor is followed by an expression representing the value of the output expression at this location, in which the model is the object passed to the template.
C # code in @{}, C # code can also be mixed with HTML code
<!DOCTYPE HTML><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"/> <title></title></Head><Body> <ul>@{for (int i = 0; I<Ten; i++) {<li>@i</Li> } } </ul></Body></HTML>
2, use Razor in general handlers:
The Razor object parses the read-cshtml into an assembly using the Parse method, and then generates the HTML.
Public voidProcessRequest (HttpContext context) {context. Response.ContentType="text/html"; stringFullpath=context. Server.MapPath (@"~/razordemo/razor1.cshtml");//get the cshtml file path stringCshtml=file.readalltext (FullPath);//get the file contents stringhtml = razor.parse (cshtml);//Parse cshtml file parsing to get HTMLcontext. Response.Write (HTML); }
3, how to read the value of an object in a cshtml file
Another overload of the Razor.parse () method is to pass in a model object, which can be used to point out the properties of an object in the cshtml file.
Parsing in a generic handler:
New Dog (); - ; - ; string html = razor.parse (cshtml, dog); Context. Response.Write (HTML);
To read the object properties in cshtml:
<!DOCTYPE HTML><HTMLxmlns= "http://www.w3.org/1999/xhtml"><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"/> <title></title></Head><Body> <H1>Dog Info:</H1> <H1>ID: @Model. ID</H1> <H1>Height: @Model. Height</H1> </Body></HTML>
Using the Razor template engine in non-MVC