RazorEngine and parsing physical view files always causes exception

前端 未结 3 423
悲&欢浪女
悲&欢浪女 2021-02-02 18:10

I have the following RazorEngine call:

public class RazorEngineRender
{
    public static string RenderPartialViewToString(string templatePath, string viewName,          


        
相关标签:
3条回答
  • 2021-02-02 18:15

    The accepted answer was perfect in 2011 (I believe pre-v3 of RazorEngine) but this code is now marked as obsolete in latest version (in time of typing it is 3.7.3).

    For newer version your method can be typed like this:

    public static string RenderPartialViewToString<T>(string templatePath, string templateName, string viewName, T model)
            {
                string template = File.ReadAllText(Path.Combine(templatePath, viewName));
                string renderedText = Engine.Razor.RunCompile(template, templateName, typeof(T), model);
                return renderedText;
            }
    

    and in order for it to work you need to add

    using RazorEngine.Templating;
    
    0 讨论(0)
  • 2021-02-02 18:18

    If you make the call like so:

    Razor.Parse(System.IO.File.ReadAllText(YourPath), 
                new { ActivationLink = activationLink });
    

    That should give you the correct output. But after I see your method posted above I'll be able to make a determination where the problem lies.

    Update

    Change your method to the following:

    public class RazorEngineRender {
        public static string RenderPartialViewToString<T>(string templatePath, string viewName, T model) {            
            string text = System.IO.File.ReadAllText(Path.Combine(templatePath, viewName));
            string renderedText = Razor.Parse(text, model);
            return renderedText;
        }
    }
    

    and you can call it like you do above.

    The reason it doesn't work is because you're telling the Parser that the model is of type object rather than passing in what type it really is. In this case an anonymous type.

    0 讨论(0)
  • 2021-02-02 18:34

    Here are a few hints you might try:

    1. Make your razor view strongly typed to a model:

      @model Foo
      <div>
          <div>
              Link: 
              <a href="@Model.ActivationLink" style="color:#666" target="_blank">
                  @Model.ActivationLink
              </a>
          </div>
      </div>
      
    2. When rendering it pass a Foo model:

      _emailService.Render(
          TemplatePath, 
          "Email.cshtml", 
          new Foo { ActivationLink = activationLink }
      )
      
    3. If you are trying to send emails from your Views make sure you checkout Postal before reinventing something.

    0 讨论(0)
提交回复
热议问题