I am using Json.net to convert a json string into a dynamic. When I use this dynamic as a model for a Razor template, I am getting an error…
Unable to compile template. ‘Newtonsoft.Json.Linq.JObject’ does not
contain a definition for ‘Name’ and no extension method ‘Name’
accepting a first argument of type ‘Newtonsoft.Json.Linq.JObject’
could be found (are you missing a using directive or an assembly
reference?)
If I just use a simple anonymous object as the model, it works fine.
Here is the problem displayed in a simple console app where I used NuGet to pull in two libraries…Newtonsoft JSON and RazorEngine.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// template used for generation
var template = "<div>Hello @Model.Name</div>";
// create model
dynamic model = new System.Dynamic.ExpandoObject();
model.Name = "Foo";
// this works just fine
RazorEngine.Razor.Parse(template, model);
// convert model to string
var json = Newtonsoft.Json.JsonConvert.SerializeObject(model);
// regenerate model
model = Newtonsoft.Json.Linq.JObject.Parse(json);
// this prints 'Foo' to the console just fine so the model is valid!
string name = model.Name;
System.Diagnostics.Debug.WriteLine(name);
// this throws the error above!
RazorEngine.Razor.Parse(template, model);
}
}
}
Can someone help me with the problem here?
You can’t directly pass the
JObjectsinto theRazorEnginebecause whenever you assign a value to theJObjectthey are stored as typeJValue. When you try to retrieve the assigned value also you will get aJValuenot the assigned one.Ex.