Razor in asp.net web project

I am currently studying viewing mechanisms, and Razor Views have become very interesting to me. I am developing an asp.net 4.0 web form application. Razor looks at examples from what I can find, mainly with MVC applications.

Can I integrate Razor views into a web form application? Is it useful to do this? The main reason I want to do this is to create a new layer for the application architecture and possibly a new area that can be tested.

+5
source share
1 answer

Of course you can! Using the Microsoft WebPages project , you can load razor classes in the same way as you normally load UserControl, specifying the class path / razor file. You will return to the WebPage instance that you can execute, and this will give you a string that you can print on your page.

I did it myself, implemented the Razor Function for Composite C1 CMS , and the source code for it is freely available from http://compositec1contrib.codeplex.com/ . Here I will talk about the important parts.

Make sure you have an assembly provider for the .cshtml files registered in the web.config file

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

.cshtml, var webPage = WebPage.CreateInstanceFromVirtualPath(_relativeFilePath); (. )

Razor

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();

WebForms

+3

All Articles