Skip to content

Strongly typed model

Alexander Selishchev edited this page Aug 2, 2021 · 11 revisions

RazorEngineCode uses slightly different approach on strongly typed model, instead model it forces you to use template base: either existing RazorEngineTemplateBase<T> or your own that inherits RazorEngineTemplateBase.

With this approach you are not bounded by typical MVC keywords and can easily introduce your own.

RazorEngineTemplateBase

IRazorEngine razorEngine = new RazorEngine();
string content = "Hello @Model.Name";

// yeah, heavy definition
IRazorEngineCompiledTemplate<RazorEngineTemplateBase<TestModel>> template = razorEngine.Compile<RazorEngineTemplateBase<TestModel>>(content);

string result = template.Run(instance =>
{
    instance.Model = new TestModel()
    {
        Name = "Hello",
        Items = new[] {3, 1, 2}
    };
});

Console.WriteLine(result);

Custom template base

public class CustomTemplateBase : RazorEngineTemplateBase
{
    public int A { get; set; }
    public string B { get; set; }
    public new MyModel Model { get; set; }

    public string Decorator(object value)
    {
        return "-=" + value + "=-";
    }
}
string content = @"Hello @A, @B, @Decorator(123) @Model.Membership.Level";

IRazorEngine razorEngine = new RazorEngine();
IRazorEngineCompiledTemplate<CustomTemplateBase> template = razorEngine.Compile<CustomTemplateBase>(content);

string result = template.Run(instance =>
{
    instance.A = 10;
    instance.B = "Alex";
    instance.Model = model; 
});

Console.WriteLine(result);