Using RazorEngine inside ASP.net MVC views
Recently while searching for a way to do runtime Razor parsing I found the RazorEngine at http://razorengine.codeplex.com/. It’s pretty simple – it allows you parse Razor syntax template strings on the fly and render them. However, support for using with MVC View is fairly limited. However, with a bit of simple creativity you can get a long way.
Here is a code sample:
Here are the main points:
- The RazorEngine is accessed by calling the “Razor” static class as seen on line 9.
- The string template is created in line 3.
- To get output, we pass a string template, plus a model, to “Razor.Parse” which produces the output.
- In this case we are passing an anonymous object with a property “Action”, which is the Func delegate on starting on line 5.
The reason we’re passing a delegate here to call the Html.Action method instead of passing the Html object itself is that we cannot get extensions method support easily with the RazorEngine parser.
- When parsed and executed, the template calls the Action delegate that is on the Model object available to it. This call then executes Html.Action and returns the string output, which is then in-lined with the remainder of the template.
The results are simple:
Template Action: (Render: 56844b67-a1ea-4184-9daf-79036778467a)
Everything after “Template Action:” comes from the child action which is parsed from the string template and executed .
My ultimate goal would be to do runtime parsing that has the same affect as using the ShortCodes api in WordPress.