RazorEngine和解析物理视图文件总是会导致异常 [英] RazorEngine and parsing physical view files always causes exception

查看:127
本文介绍了RazorEngine和解析物理视图文件总是会导致异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下RazorEngine调用:

I have the following RazorEngine call:

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;
    }
}

这是从以下位置调用的:

This is called from:

_emailService.Render(TemplatePath, "Email.cshtml", new { ActivationLink = activationLink });

我也有此查看文件(email.cshtml):

I also have this view file (email.cshtml):

    <div>
      <div>
            Link: <a href="@Model.ActivationLink" style="color:#666" target="_blank">@Model.ActivationLink</a>
      </div>
    </div>

当对Razor.Parse()的调用发生时,我总是得到: 无法编译模板.查看错误"列表以获取详细信息.

When the call to Razor.Parse() occurs, I always get a: Unable to compile template. Check the Errors list for details.

错误列表为:

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 

我已经尝试了所有在阳光下进行的操作,包括尝试使用具体类型而不是匿名类型,在视图文件的顶部声明@Model行,但是没有运气.我想知道图书馆是出了问题还是我自己?

I've tried everything under the sun, including trying a concrete type as opposed to anonymous type, declaring the @Model line at the top of the view file but no luck. I'm wondering if the library is at fault or definately me?

顺便说一句,我所指的razorengine在codeplex可用: RazorEngine

By the way, the razorengine I am referring to is available here at codeplex: RazorEngine

推荐答案

如果您这样拨打电话:

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.

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

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.

之所以不起作用,是因为您要告诉Parser该模型属于对象类型,而不是传递其实际类型.在这种情况下,匿名类型.

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.

这篇关于RazorEngine和解析物理视图文件总是会导致异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆