Framework Madness!

And other adventures C# and asp.net …

Archive for April 2011

Using RazorEngine inside ASP.net MVC views

leave a comment »

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:

Code Snippet
  1. @using RazorEngine;
  2. @{
  3.     var Template = "Template Action: @Model.Action(\"Index\",\"Render\",new {Area=\"Testing\"})";
  4.  
  5.     Func<String, String, Object, MvcHtmlString> Action = (action, controller, values) =>
  6.                                                              {
  7.                                                                  return Html.Action(action, controller, values);
  8.                                                              };}
  9. @Razor.Parse(Template, new { Action = Action })

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.

Written by Lynn Eriksen

April 20, 2011 at 8:24 pm

Posted in Uncategorized