This project is read-only.

Small coding tip needed with RazorEngine

Dec 18, 2011 at 9:09 PM


Assume that I have a Widget class with two string columns: "HTML", and "JSON".

HTML might contain something link: "<div class='haha'><h2>@Model.Title</h2><p>@Model.Text</p>"

And, correspondingly, in this particular example, JSON will contain the values but in JSON format: { "Title":"Some Title", "Text":"Some Text" }

My goal is to return a string that will use the template in the HTML column and populate it with values from the JSON field.

            var model = ////what do I do here with w.JSON?///

            string result = Razor.Parse(w.HTML, model);

            return result;




Dec 21, 2011 at 1:55 AM

You can use the JavaScriptSerializer (System.Web.Extensions) to achieve this with either a strongly typed class or a dynamic object such as:

class Program
        static void Main(string[] args)
            var template = "<div class='haha'><h2>@Model.Title</h2><p>@Model.Text</p>";
            var json = "{ \"Title\":\"Some Title\", \"Text\":\"Some Text\" }";
            var ser = new JavaScriptSerializer();
            var model = ser.Deserialize<MyClass>(json);
            var obj = ser.Deserialize<dynamic>(json);
            var result = RazorEngine.Razor.Parse(template, model);
            result = RazorEngine.Razor.Parse(template, new {Title = obj["Title"], Text = obj["Text"]});

    public class MyClass
        public string Title { get; set; }
        public string Text { get; set; }

Dec 21, 2011 at 1:59 AM

Thing is that I don't know the parameter names to expect. (Title/Text). The template should be totally flexible, having any number of properties with any names, and the JSON should supply values for them.

Anyway, I found the solution on StackOverflow: