razor views in asp.net web project

半城伤御伤魂 提交于 2019-12-19 07:32:09

问题


I am currently researching view engines and Razor Views have become very interesting to me. I am in process of developing an asp.net 4.0 web forms application. Razor views examples from what I could find are predominantly with MVC applications.

Is it possible to integrate Razor views in to a web forms application? Is it beneficial to do so? The main reason I look to do this is to create a new layer for my applications architecture and possibly a new area that can be tested.


回答1:


Of course you can! By using the WebPages project from Microsoft you can load razor-classes the same way you would normally load an UserControl, by giving a path to a class/razor file. What you get back is an instance of a WebPage that you can execute and that will give you a string you can print out on your page.

I've done this myself, implemented Razor functionality for Composite C1 CMS and the sourcecode for it is freely available from http://compositec1contrib.codeplex.com/. I'll highlight the important parts here.

Make sure you have a build provider for .cshtml files registered in the web.config

Make sure you have the necessary system.web.webPages.razor configuration setup

Instantiate an instance of a .cshtml file like this var webPage = WebPage.CreateInstanceFromVirtualPath(_relativeFilePath); (see doc)

Get the output of the Razor class like this

var httpContext = new HttpContextWrapper(HttpContext.Current);
var pageContext = new WebPageContext(httpContext, webPage, null);

var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
{
   webPage.ExecutePageHierarchy(pageContext, writer);
}

string output = sb.ToString();

Just output the string on your WebForms Page



来源:https://stackoverflow.com/questions/8129712/razor-views-in-asp-net-web-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!