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

网络编程 2021-07-04 22:41www.168986.cn编程入门
这篇文章主要介绍了asp.net实现在非MVC中使用Razor模板引擎的方法,较为详细的分析了Razor模板引擎的使用技巧,需要的朋友可以参考下

本文实例讲述了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程序设计有所帮助。

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by

长沙网络推广|微博营销|长沙seo优化|视频营销|长沙网络营销|微信营销|长沙网站建设|口碑营销|软文营销