本文實例講述了asp.net實現(xiàn)在非MVC中使用Razor模板引擎的方法。分享給大家供大家參考。具體分析如下:
模板引擎介紹
Razor、Nvelocity、Vtemplate,Razor一般在MVC項目中使用,這里介紹在非MVC項目中的用法。
如何在非MVC中使用Razor模板引擎
借助于開源的RazorEngine,我們可以在非asp.net mvc項目中使用Razor引擎,甚至在控制臺、WinForm項目中都可以使用Razor(自己開發(fā)代碼生成器)
如何使用Razor
環(huán)境搭建:
① 添加引用RazorEngine.dll
② 創(chuàng)建cshtml
新建一個html,改名為cshtml。注意:通過 添加--html頁再改成cshtml的方式打開是么有自動提示的,必須關(guān)掉該文件重新打開。推薦使用,添加--新建項--html頁在這里直接改成cshtml創(chuàng)建cshtml文件,直接可用自動提示。

開始使用:
1. 在cshtml中使用Razor語法
Razor中@后面跟表達式表示在這個位置輸出表達式的值,模板中Model為傳遞給模板的對象。
@{}中為C#代碼,C#代碼還可以和html代碼混排
!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>
ul>
@{
for (int i = 0; i 10; i++)
{
li>
@
i/li>
}
}
/ul>
/body>
/html>
2. 在一般處理程序中使用Razor:
Razor對象會使用Parse方法將讀取到的cshtml解析為一個程序集,再生成html。
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
string fullPath=context.Server.MapPath(@"~/Razordemo/Razor1.cshtml");
//拿到cshtml文件路徑
string cshtml=File.ReadAllText(fullPath);//得到文件內(nèi)容
string html = Razor.Parse(cshtml);//解析cshtml文件解析得到html
context.Response.Write(html);
}
3. 如何在cshtml文件讀取對象的值
Razor.Parse()方法的另一個重載就是傳進一個Model對象,在cshtml文件中通過Model就可以點出來對象的屬性。
在一般處理程序中解析:
Dog dog = new Dog();
dog.Id = 100;
dog.Height = 120;
string html = Razor.Parse(cshtml, dog);
context.Response.Write(html);
在cshtml中讀取對象屬性:
!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>
h1>狗狗信息:/h1>
h1>Id:@Model.Id/h1>
h1>身高:@Model.Height/h1>
/body>
/html>
希望本文所述對大家的asp.net程序設(shè)計有所幫助。
您可能感興趣的文章:- 使用Asp.net Mvc3 Razor視圖方式擴展JQuery UI Widgets方法介紹
- ASP.NET MVC4 Razor模板簡易分頁效果
- Asp.net MVC中Razor常見的問題與解決方法總結(jié)
- 詳解ASP.NET MVC 利用Razor引擎生成靜態(tài)頁
- ASP.NET MVC學(xué)習(xí)教程之Razor語法