国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 網站 > 建站經驗 > 正文

asp.net模板引擎Razo-r調用外部方法用法實例

2019-11-02 15:42:01
字體:
來源:轉載
供稿:網友

 首先使用Razor的步驟:讀取cshtml、解析cshtml同時指定cacheName。

而這個步驟是重復的,為了遵循DRY原則,將這段代碼封裝為一個RazorHelper()方法

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; } }

如何在cshtml中用Razor調用外部方法

1. 首先在cshtml文件引用test1和test2所在類的命名空間

1 2 3 4 5 6 7 8 9 10 11 12 @using WebTest1.RazorDemo;<!--test1和test2所在類的命名空間--> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> @RazorTest.test1()<br /> @RazorTest.test2() </body> </html>

2. 在一般處理程序中調用RazorHelper.ParseRazor(),將讀取到的cshtml文件返回給客戶

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); }

為什么要在cshtml文件中調用方法呢?

先看一個繁瑣的,在cshtml中插入checkbox的處理

1. 一般處理程序

1 2 bool gender = true; string html = RazorHelper.ParseRazor(context, @"~/Razordemo/Razor2.cshtml", new { Gender = gender });

2. cshtml文件中處理checkbox的checked狀態

<input type="checkbox" @(Model.Gender?"checked":"") />
<!--加括號改變優先級,否則編譯器會將點Model后面的表達式當字符串處理-->

是不是很亂?處女座不能忍。

我們知道方法可以封裝一些重復代碼,調用方法讓cshtml頁面更簡潔。

舉個例子:

要在cshtml頁面插入一個checkbox。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 石楼县| 通城县| 中卫市| 吴桥县| 磴口县| 惠州市| 棋牌| 温州市| 彰化县| 阿拉善盟| 平顺县| 睢宁县| 常州市| 阿克| 秦安县| 西乌珠穆沁旗| 普洱| 贡嘎县| 佛教| 崇阳县| 通州区| 静安区| 嘉峪关市| 诏安县| 奇台县| 繁峙县| 吉水县| 饶平县| 娄底市| 白水县| 三江| 赫章县| 中山市| 南宫市| 元阳县| 青浦区| 高邑县| 泊头市| 吉木萨尔县| 犍为县| 丘北县|