gpt4 book ai didi

c# - RazorEngine 和布局的 TemplateCompilationError

转载 作者:可可西里 更新时间:2023-11-01 09:08:14 24 4
gpt4 key购买 nike

我一直在尝试在我的一个小项目中使用 RazorEngine,但是当我尝试使用模板布局时无法克服这个错误。

Unable to compile template. 'object' does not contain a definition for 'Description' and no extension method 'Description' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

我的设置:我有一个这样的模板布局:

<html>
<head>
<title>@Model.Description</title>
</head>
<body>
@RenderBody()
</body>
</html>

然后是一个如下所示的页面模板:

@{
_Layout = "Layout.cshtml";
}
<h1>@Model.Description</h1>

这是我用来尝试解决这个问题的测试 Main 函数:

    static void Main(string[] args)
{
// Configuration for RazorEngine
var config = new TemplateServiceConfiguration
{
EncodedStringFactory = new RawStringFactory(),

Resolver = new DelegateTemplateResolver(name =>
{
var file = name;
var content = File.ReadAllText("Templates/" + file);
return content;
})
};

// Try to render output using Razor
using (var service = new TemplateService(config))
{
string template = File.ReadAllText("Templates/Default.cshtml");

dynamic model = new ExpandoObject();
model.Description = "This is a test";
string result = service.Parse(template, model);
Console.WriteLine(result);
if (Debugger.IsAttached)
{
Console.ReadLine();
}

}
}

知道我错过了什么吗?

更新:如果我将动态模型对象替换为具有 Description 属性的 POCO,它就会起作用。我还用

尝试了 Parse 的类型化版本

dynamic

, ExpandoObject , 和 IDictionary<string, object>但他们都有同样的错误。

更新:我在 Github 上发现了这个项目,它似乎以某种方式工作: https://github.com/mikoskinen/graze/blob/master/src/core/Graze.cs#L174

最佳答案

我认为使用模板服务的 Parse 重载更合适,它采用 ViewBag 并在您的 View 中使用 ViewBag而不是模型。

编辑:

public virtual string Parse(string razorTemplate, object model, DynamicViewBag viewBag, string cacheName)

关于c# - RazorEngine 和布局的 TemplateCompilationError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13328114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com