Home > Blockchain >  RazorEngine throws 'the name model does not exist in the current context' at runtime
RazorEngine throws 'the name model does not exist in the current context' at runtime

Time:11-30

I am using RazorEngine package to generate e-mail templates.
Here is the code for the method:

public async Task<string> GetEmailTemplateAsString<T>(string viewName, T model)
{
    var templatePath = @$"{Directory.GetCurrentDirectory()}\Views\{viewName}.cshtml";
    var template = await File.ReadAllTextAsync(templatePath);

    var html = Engine.Razor.RunCompile(template, "weeklySummary", typeof(T), model);

    return html;
}

And the view:

@model CourseWork.Core.Models.EmailTemplate.WeeklySummaryModel

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            background-color: lightgoldenrodyellow;
            font-family: Verdana, Geneva, Tahoma, sans-serif;
        }

        .greetings {
            text-align: center;
            border-bottom: 1px solid lightgray;
        }

        .main {
            display: block;
            border-bottom: 1px solid lightgray;
            text-align: center;
            padding-bottom: 21.28px;
        }

        ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        li {
            display: block;
            padding: 10px;
        }
    </style>
</head>
<body>
    <section class="greetings">
        <h1>Hello, @Model.User.DisplayName!</h1>
        <h3>Here is our weekly summary, specially for you</h3>
    </section>

    <section class="main">
        @foreach (var entry in Model.BoardThreadWithRepliesModels)
        {
            <h4>@entry.BoardName</h4>
            <h5>@entry.ThreadName</h5>
            <ul>
                @foreach (var reply in entry.Replies)
                {
                    <li>
                        <span>@reply.UserDisplayName</span>
                        <p>@reply.Content</p>
                        <img src="@reply.PicRelatedPath" alt="pic-related" />
                    </li>
                }
            </ul>
        }
    </section>
</body>
</html>

After I run the app, I get CS0103 error with the description stated in the title of the question.

I have tried googling the error message, but, mainly, all the results have been related to IntelliSense not working, which is not my case at all.

UPD: The calling code:

*Dapper query*

var fullModel = new WeeklySummaryModel
{
    User = user,
    BoardThreadWithRepliesModels = models
};

return await _emailTemplateHelper.GetEmailTemplateAsString("WeeklySummary", fullModel);

UPD2: The exception stated that there is an issue on line 14 char 18. It turned out to be situated in auto-generated code:

// <auto-generated/>
#pragma warning disable 1591
namespace CompiledRazorTemplates.Dynamic
{
    #line hidden
    using System.Threading.Tasks;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    internal class RazorEngine_00fefb8ea0984fabaf601e182158fa32 : RazorEngine.Templating.TemplateBase<dynamic>
    {
        #pragma warning disable 1998
        public async override global::System.Threading.Tasks.Task ExecuteAsync()
        {
            Write(model);
            WriteLiteral(@" CourseWork.Core.Models.EmailTemplate.WeeklySummaryModel

<html lang=""en"">
<head>
    <meta charset=""UTF-8"">
    <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
    <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
    <title>Document</title>
    <style>
        body {
            background-color: lightgoldenrodyellow;
            font-family: Verdana, Geneva, Tahoma, sans-serif;
        }

        .greetings {
            text-align: center;
            border-bottom: 1px solid lightgray;
        }

        .main {
            display: block;
            border-bottom: 1px solid lightgray;
            text-align: center;
            padding-bottom: 21.28px;
        }

        ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        li {
            display: block;
            padding: 10px;
        }
    </style>
</head>
<body>
    <section greetings"">
        <h1>Hello, ");
                          Write(Model.User.DisplayName);
            WriteLiteral("!</h1>\r\n        <h3>Here is our weekly summary, specially for you</h3>\r\n    </section>\r\n\r\n    <section class=\"main\">\r\n");
                     foreach (var entry in Model.BoardThreadWithRepliesModels)
        {
            WriteLiteral("            <h4>");
                       Write(entry.BoardName);
            WriteLiteral("</h4>\r\n            <h5>");
                       Write(entry.ThreadName);
            WriteLiteral("</h5>\r\n            <ul>\r\n");
                             foreach (var reply in entry.Replies)
                {
            WriteLiteral("                    <li>\r\n                        <span>");
                                     Write(reply.UserDisplayName);
            WriteLiteral("</span>\r\n                        <p>");
                                  Write(reply.Content);
            WriteLiteral("</p>\r\n                        <img");
            BeginWriteAttribute("src", " src=\"", 1563, "\"", 1590, 1);
            WriteAttributeValue("", 1569, reply.PicRelatedPath, 1569, 21, false);
            EndWriteAttribute();
            WriteLiteral(" alt=\"pic-related\" />\r\n                    </li>\r\n");
                            }
            WriteLiteral("            </ul>\r\n");
                    }
            WriteLiteral("    </section>\r\n</body>\r\n</html>");
        }
        #pragma warning restore 1998
    }
}
#pragma warning restore 1591

------------- END -----------

CodePudding user response:

RazorEngine is a custom library built on top of Microsoft's Razor view engine. It doesn't have all capabilities you might be familiar with from MVC and Razor pages.

Just drop the @model directive. It should work, but if it doesn't, Visual Studio doesn't help much in the sense of IntelliSense anyway.

CodePudding user response:

This error:

The name 'model' does not exist in the current context

commonly occurs when you try to reference the instance of the model within the template with a lower case m.

As explained here, the type of the model is defined using the lowercase @model but to reference the instance of the model you must use the upper case @Model or Model.

I cannot see nay incorrect reference to the view model in your script, but that doesn't mean it is not there.

Try downgrading the nuget package, the version 3 runtime full exception should contain more information like this:

Errors while compiling a Template.
Please try the following to solve the situation:
  * If the problem is about missing/invalid references or multiple defines either try to load 
    the missing references manually (in the compiling appdomain!) or
    Specify your references manually by providing your own IReferenceResolver implementation.
    See https://antaris.github.io/RazorEngine/ReferenceResolver.html for details.
    Currently all references have to be available as files!
  * If you get 'class' does not contain a definition for 'member': 
        try another modelType (for example 'null' to make the model dynamic).
        NOTE: You CANNOT use typeof(dynamic) to make the model dynamic!
    Or try to use static instead of anonymous/dynamic types.
More details about the error:
 - error: (126, 58) The name 'model' does not exist in the current context
Temporary files of the compilation can be found in (please delete the folder):
...

It should contain the line number and character number of the incorrect reference as well as the temporary file location where the template was being compiled.

  • Related