RazorEngine和解析物理视图文件总是会导致异常

jaf*_*ffa 13 asp.net-mvc razor

我有以下RazorEngine电话:

public class RazorEngineRender
{
    public static string RenderPartialViewToString(string templatePath, string viewName, object model)
    {            
        string text = System.IO.File.ReadAllText(Path.Combine(templatePath, viewName));
        string renderedText = Razor.Parse(text, model);
        return renderedText;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是从:

_emailService.Render(TemplatePath, "Email.cshtml", new { ActivationLink = activationLink });
Run Code Online (Sandbox Code Playgroud)

我也有这个视图文件(email.cshtml):

    <div>
      <div>
            Link: <a href="@Model.ActivationLink" style="color:#666" target="_blank">@Model.ActivationLink</a>
      </div>
    </div>
Run Code Online (Sandbox Code Playgroud)

当调用Razor.Parse()时,我总是得到一个:无法编译模板.检查错误列表以获取详细信息.

错误列表是:

error CS1061: 'object' does not contain a definition for 'ActivationLink' and no extension method 'ActivationLink' accepting a first argument of type 'object' could be found 
Run Code Online (Sandbox Code Playgroud)

我已经在阳光下尝试了一切,包括尝试一种具体类型而不是匿名类型,在视图文件的顶部声明@Model行但没有运气.我想知道图书馆是错还是肯定是我?

顺便说一下,我所指的razorengine可以在codeplex: RazorEngine上找到

Bui*_*ted 18

如果您这样打电话:

Razor.Parse(System.IO.File.ReadAllText(YourPath), 
            new { ActivationLink = activationLink });
Run Code Online (Sandbox Code Playgroud)

这应该给你正确的输出.但是,在我看到上面发布的方法之后,我将能够确定问题所在.

更新

将您的方法更改为以下内容:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以像上面那样打电话给它.

它不起作用的原因是因为你告诉Parser模型是object类型而不是传递它真正的类型.在这种情况下是匿名类型.


Zor*_* P. 6

接受的答案在2011年是完美的(我相信RazorEngine的前3版)但是这个代码现在在最新版本中被标记为过时(在键入时为3.7.3).

对于较新版本,您的方法可以像这样输入:

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;
        }
Run Code Online (Sandbox Code Playgroud)

为了使它工作,你需要添加

using RazorEngine.Templating;
Run Code Online (Sandbox Code Playgroud)