razor views in asp.net web project

2019-02-17 18:37发布

问题:

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