Skip to content

@Model is null when using RazorEngineTemplateBase #28

Open
@kobynz

Description

@kobynz

I've run into an issue when attempting to strongly type a template.
My template has @inherits RazorEngineCore.RazorEngineTemplateBase<MyModelType> at the top, and this makes intellisense work nicely.

The template compiles just fine, but when I run it, I always get "Object not sent to instance of an object" when I reference any property on my model. I know my model is not null. It works fine when render it without using RazorEngineTemplateBase.

Running a template with @(Model == null) works, but always renders "True".

My generic render function:

private static ConcurrentDictionary<int, IRazorEngineCompiledTemplate<IRazorEngineTemplate>> TemplateCache = 
            new ConcurrentDictionary<int, IRazorEngineCompiledTemplate<IRazorEngineTemplate>>();

public static string Render<TModel>(string template, TModel model, Assembly[] referencedAssemblies = null)
        {
            int templateHashCode = template.GetHashCode();

            var compiledTemplate = TemplateCache.GetOrAdd(templateHashCode, i =>
            {
                var razorEngine = new RazorEngine();

                var compiledTemplate = razorEngine.Compile<RazorEngineTemplateBase<TModel>>(template, builder =>
                {
                    ...
                });

                return compiledTemplate;
            });

            return compiledTemplate.Run(instance =>
            {
                instance.Model = model;
            });
        }

Any help on this would be greatly appreciated. Thanks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions