怎么在ASP.NET WebForm中使用Razor视图引擎

怎么在ASP.NET WebForm中使用Razor视图引擎

前几天微软发布了一堆新技术,详见ScottGu的博客:

Announcing release of ASP.NET MVC 3, IIS Express, SQL CE 4, Web Farm Framework, Orchard, WebMatrix
http://weblogs.asp.net/scottgu/archive/2011/01/13/announcing-release-of-asp-net-mvc-3-iis-express-sql-ce-4-web-farm-framework-orchard-webmatrix.aspx

 

让人特别感兴趣的是ASP.NET MVC 3和WebMatrix中的Razor视图引擎,其简洁明了的句法给人以耳目一新的感觉,ScottGu对它做了很多介绍,详见上面链接中有关Razor部分的内容和链接。

但这些介绍基本上是围绕着ASP.NET MVC 3来进行的,在WebForm中是否能够用它来渲染视图呢?可以的,这里做一个简单的示范:

安装ASP.NET MVC 3,在你的web应用中添加对System.Web.WebPages程序集的引用。

在项目中添加一个.cshtml文件(假定你的项目是基于C#的),在这里我生成了一个weibo.cshtml,其中的内容为:

 

欢迎去 @Model.Name 的新浪微博 <a href=”@Model.URL”>@Model.URL</a> 拍砖!

 

所用的Model是一个自定义类:

public class UserInfo
{
    public string Name { get; set; }
    public string URL { get; set; }
}

在你Page的HTML中加一个Panel:

<asp:Panel ID=”pnlContent” runat=”server” />

然后在Page_Load方法中,

var model = new UserInfo { Name = “思归”, URL = “http://t.sina.com.cn/timeflieslikeanarrow” };

var path = System.IO.Path.Combine(Request.ApplicationPath, “weibo.cshtml”);
var type = BuildManager.GetCompiledType(path);

System.Diagnostics.Debug.Assert(type != null);

var script = Activator.CreateInstance(type) as System.Web.WebPages.WebPage;

System.Diagnostics.Debug.Assert(script != null);

var writer = new System.IO.StringWriter();

script.ExecutePageHierarchy(new System.Web.WebPages.WebPageContext(new System.Web.HttpContextWrapper(HttpContext.Current),
                                null, //rendering page
                                model), //model
                          writer);

pnlContent.Controls.Add(new LiteralControl(writer.ToString()));

 

运行该网页,你会看到这样的输出:

 

欢迎去 思归 的新浪微博 http://t.sina.com.cn/timeflieslikeanarrow 拍砖!

 

参考:

WebMatrix and DNN – 5 – Hosting the Razor Engine
http://www.dotnetnuke.com/Resources/Blogs/tabid/825/EntryId/2858/WebMatrix-and-DNN-ndash-5-ndash-Hosting-the-Razor-Engine.aspx

Hosting the Razor Engine for Templating in Non-Web Applications
http://west-wind.com/Weblog/posts/864461.aspx

Razor Templating Engine
http://razorengine.codeplex.com/

This entry was posted in 未分类. Bookmark the permalink.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值