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
1 2 3 4 5 6 7 8 9 10 11 |
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
1 2 3 4 5 6 7 8 9 10 11-12 |
@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
1 2 3 4 5 6 |
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
1 2 |
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
1 2 3 4 5 6 7 8 9 10 11 |
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
1 2 |
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
1 2 3 4 5 6 7 8 9 all |
@using webtest1.razordemo;<!--Test1 and test2 the namespace of the class--> <! DOCTYPE html> |