您的位置:首页 > 编程语言 > ASP

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

2012-06-29 12:53 357 查看

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

Posted on

2011 年 01 月 15 日 by
saucer

前几天微软发布了一堆新技术,详见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.

← 更多WP7开发资源
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息