Search code examples
razorrazorengine

Engine.Razor.Run causes InvalidCastException


I have the following code to get my cshtml Email Template.

try
            {

            var layoutTemplateKey = new NameOnlyTemplateKey("layout", ResolveType.Global, null);
            if (!Engine.Razor.IsTemplateCached(layoutTemplateKey, null))
                Engine.Razor.AddTemplate(layoutTemplateKey, ReadTemplateFile("/Views/Email/Layout.cshtml"));

            var templateKey = new NameOnlyTemplateKey(templatePath, ResolveType.Global, null);
            if (!Engine.Razor.IsTemplateCached(templateKey, viewModel.GetType()))
            {
                Engine.Razor.AddTemplate(templateKey, ReadTemplateFile(templatePath));
                Engine.Razor.Compile(templateKey, viewModel.GetType());
            }

            return viewModel == null ?
                Engine.Razor.Run(templateKey) :
                Engine.Razor.Run(templateKey, viewModel.GetType(), viewModel);

            }
            catch (Exception ex)
            {
                return ex.Message;
            }

However My the Engine.Razor.Run causes InvalidCastException with a model which is no where referenced here.

And it continuously happens with any other models too.

The recent change I was done was inheriting each of this class by another Model to be used in the Layout.cshtml.

Expected Model: NewBookRecievedEmailViewModel

public class NewBookRecievedEmailViewModel : EmailHelperModel
    {
        public ProposalPostedEmailViewModel()
        {
            this.canBeDeleted = true;
        }

        public string BookName { get; set; }

        public string Author {get; set;}
    }

Gets error with Model PayOutBookEmailViewModel

public class PayOutBookEmailViewModel : EmailHelperModel
    {
        public string BookID { get; set; }

        public string BookUrl {get; set;}
    }

And the inherited Model is : EmailHelper

public class EmailHelperModel
    {
        public bool canBeDeleted { get; set;  }
        public string DeleteUrl { get; set; }
    }

Stack Trace:

   at RazorEngine.Templating.TemplateBase`1.SetModel(Object model)
   at RazorEngine.Templating.TemplateBase.SetData(Object model, DynamicViewBag viewbag)
   at RazorEngine.Templating.RazorEngineCore.CreateTemplate(ICompiledTemplate template, Object model, DynamicViewBag viewbag)
   at RazorEngine.Templating.RazorEngineCoreWithCache.ResolveInternal(String cacheName, Object model, Type modelType, DynamicViewBag viewbag, ResolveType resolveType, ITemplateKey context)
   at RazorEngine.Templating.InternalTemplateService.Resolve(String name, Object model, Type modelType, DynamicViewBag viewbag, ResolveType resolveType)
   at RazorEngine.Templating.TemplateBase`1.ResolveLayout(String name)
   at RazorEngine.Templating.TemplateBase.RazorEngine.Templating.ITemplate.Run(ExecuteContext context, TextWriter reader)
   at RazorEngine.Templating.RazorEngineCore.RunTemplate(ICompiledTemplate template, TextWriter writer, Object model, DynamicViewBag viewBag)
   at RazorEngine.Templating.RazorEngineService.Run(ITemplateKey key, TextWriter writer, Type modelType, Object model, DynamicViewBag viewBag)
   at RazorEngine.Templating.DynamicWrapperService.Run(ITemplateKey key, TextWriter writer, Type modelType, Object model, DynamicViewBag viewBag)
   at RazorEngine.Templating.RazorEngineServiceExtensions.<>c__DisplayClass22_0.<Run>b__0(TextWriter writer)
   at RazorEngine.Templating.RazorEngineServiceExtensions.WithWriter(Action`1 withWriter)
   at RazorEngine.Templating.RazorEngineServiceExtensions.Run(IRazorEngineService service, ITemplateKey key, Type modelType, Object model, DynamicViewBag viewBag)
   at Pxp.Api.Helpers.EmailHelper.GetHtmlContent(String templatePath, Object viewModel)

Solution

  • Instead of using cshtml, consider using actual HTML; or better yet, generating elements with JavaScript, it's the real way-to-go, here' some sample code of how to create an element in JavaScript:

    var MyEngine = new (function() {
         this.el = function(opts) {
            if(!svgList.split(" ").find(x => x == opts.tag)) {
                this.node = document.createElement(opts.tag || "div");
            } else {
                this.node = document.createElementNS('http://www.w3.org/2000/svg', opts.tag);
            } 
    
            for(var k in opts) {
                if(k == "style") {
                    for(var s in opts[k]) {
                        this.node.style[s] = opts[k][s];
                    }
                } else if(k != "parent"){
                    this.node[k] = opts[k];
                }
            }
    
    
    
            this.setAttrs = (attrs) => {
                for(var k in attrs) {
                    this.node.setAttribute(k, attrs[k]);
                }
            };
            this.getAttr = (at) => {
                return this.node.getAttribute(at);
            };
    
            this.setStyle = (stl) => {
                for(var k in stl) {
                    this.node.style[k] = stl[k];
                }
            }
    
            var attr = opts.attr || {};
            this.setAttrs(attr);
            var optsPar = opts.parent;
            var par = null;
            if(optsPar) {
                if(optsPar.constructor == String) {
                    par = f("#" + optsPar);
                } else if(optsPar instanceof Element) {
                    par = optsPar;
                }
            }
    
            this.parent = par || document.body || {appendChild: (d) => {}};
            this.parent.appendChild(this.node);
         };
    )();
    

    then to create a new element:

    var temp = new MyEngine.el({
        id:"hi",
        style:{position:absolute, left:100+"px"},
        innerHTML:"<b>nice to meet you</b>
    });