Search code examples
c#razorengine

Razor Engine Dynamic Template Model Members


The following code produces "WTF??"

var t = @"@((Model.Type as Type == null)?""WTF??"":""Makes Sense"")";
var s = Engine.Razor.RunCompile(t, Guid.NewGuid().ToString(), null, new { Type = typeof(DateTime)});
Console.WriteLine(s);

It appears that Model.Type is of type RazorDynamicObject. How do I cast it safely back to type?

Thanks!


Solution

  • You don't. This is a weird side effect of the fact that you start with a anonymous class, which is internal and needs to be wrapped.

    RazorDynamicObject does wrap all calls again to be able to handle anonymous types of properties. RazorDynamicObject is designed in a way so that it even works across Appdomains (isolation).

    If you need a concrete instance you need use a concrete class. Maybe there should be an option to disable the recursive wrapping. Please open an issue on the github RazorEngine page, if you feel like you need that feature.

    Edit: This is no longer true as of 3.6.2. You actually can now escape this RazorDynamicObject wrapper by casting to your concrete type. There are some hidden scenarios where we automatically escape the wrapper (but I will not go into details here). Just note that this should now "just work".

    Matthid, a RazorEngine contributor.