当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net实现在非MVC中使用Razor模板引擎的方法

asp.net实现在非MVC中使用Razor模板引擎的方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

9c8996航班,秋交会,不灭的心伴奏

本文实例讲述了asp.net实现在非mvc中使用razor模板引擎的方法。分享给大家供大家参考。具体分析如下:

模板引擎介绍

razor、nvelocity、vtemplate,razor一般在mvc项目中使用,这里介绍在非mvc项目中的用法。
如何在非mvc中使用razor模板引擎
借助于开源的razorengine,我们可以在非asp.net mvc项目中使用razor引擎,甚至在控制台、winform项目中都可以使用razor(自己开发代码生成器)

如何使用razor

环境搭建:

① 添加引用razorengine.dll
② 创建cshtml

新建一个html,改名为cshtml。注意:通过 添加--html页再改成cshtml的方式打开是么有自动提示的,必须关掉该文件重新打开。推荐使用,添加--新建项--html页在这里直接改成cshtml创建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);//得到文件内容
 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程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网