This example describes the ASP.net template engine razor calling external method usage. Share to everyone for your reference. Specifically as follows:
First use the razor steps: Read cshtml, parse cshtml and specify CacheName.
And this step is repetitive, in order to follow the dry principle, encapsulate this code as a Razorhelper () method
public class Razorhelper
{public
static string Parserazor (HttpContext context, String Cshtmlvirtualpath, Object Model
{
string fullpath = context. Server.MapPath (Cshtmlvirtualpath);
String cshtml = File.readalltext (fullpath);
String cachename = FullPath + file.getlastwritetime (fullpath);
String html = Razor.parse (cshtml,model,cachename);
return html;
}
How to call an external method with razor in cshtml
1. The namespace of the class where Test1 and Test2 are referenced first in the cshtml file
@using webtest1.razordemo;<!--Test1 and test2 the namespace of the class-->
<! DOCTYPE html>
2. Call Razorhelper.parserazor () in a generic handler to return the read cshtml file to the customer
public void ProcessRequest (HttpContext context)
{context
. Response.ContentType = "text/html";
String html = Razorhelper.parserazor (context, @ "~/razordemo/razor2.cshtml", null);
Context. Response.Write (HTML);
Why would you call a method in a cshtml file?
First look at a tedious, insert the checkbox in the cshtml processing
1. General processing procedures
BOOL gender = true;
String html = Razorhelper.parserazor (context, @ "~/razordemo/razor2.cshtml", new {Gender = Gender});
2. cshtml the checked state of the checkbox in the file
<input type= "checkbox" @ (Model.gender?) Checked ":" ")/>
<!--parentheses change the precedence, otherwise the compiler will treat the expression following the point model as a string-->
Is it messy? Virgo cannot endure.
We know that methods can encapsulate some repetitive code and invoke methods to make cshtml pages more concise.
As an example:
To insert a checkbox on the cshtml page.
1. First encapsulate a checkbox () method
public static rawstring CheckBox (string name, string ID, bool ischecked)
{
StringBuilder sb = new StringBuilder ();
sb. Append ("<input type= ' checkbox ' id= ')". Append (ID). Append ("'"). Append ("Name= '"). Append (name). Append ("'");
if (ischecked)
{
sb. Append ("checked");
}
Sb. Append ("/>");
Return to New Rawstring (sb.) ToString ());
}
2. Read and parse cshtml files in general handlers
String html = Razorhelper.parserazor (context, @ "~/razordemo/razor2.cshtml", null);
Context. Response.Write (HTML);
3. Call the checkbox () method in the Cshtml file to insert the checkbox into the cshtml
@using webtest1.razordemo;<!--Test1 and test2 the namespace of the class-->
<! DOCTYPE html>
I hope this article will help you with the ASP.net program design.