【发布时间】:2012-06-29 00:26:01
【问题描述】:
我正在使用 Json.net 将 json 字符串转换为动态字符串。当我将此动态用作 Razor 模板的模型时,出现错误...
无法编译模板。 'Newtonsoft.Json.Linq.JObject' 没有 包含“名称”的定义,没有扩展方法“名称” 接受“Newtonsoft.Json.Linq.JObject”类型的第一个参数 可以找到(您是否缺少 using 指令或程序集 参考?)
如果我只是使用一个简单的匿名对象作为模型,它就可以正常工作。
这是一个简单控制台应用程序中显示的问题,我使用 NuGet 拉入两个库...Newtonsoft JSON 和 RazorEngine。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// template used for generation
var template = "<div>Hello @Model.Name</div>";
// create model
dynamic model = new System.Dynamic.ExpandoObject();
model.Name = "Foo";
// this works just fine
RazorEngine.Razor.Parse(template, model);
// convert model to string
var json = Newtonsoft.Json.JsonConvert.SerializeObject(model);
// regenerate model
model = Newtonsoft.Json.Linq.JObject.Parse(json);
// this prints 'Foo' to the console just fine so the model is valid!
string name = model.Name;
System.Diagnostics.Debug.WriteLine(name);
// this throws the error above!
RazorEngine.Razor.Parse(template, model);
}
}
}
有人可以帮我解决这个问题吗?
【问题讨论】:
-
你试过了吗:var template = "Hello @(Convert.ToString(Model.Name))";
-
我找到了一个替代解决方案,它与我尝试对 json.net (bit.ly/KHAGVs) 做的事情相同。这是最终的解决方案,但这一切都始于这篇博文 (bit.ly/KHALsd)。
标签: asp.net-mvc razor asp.net-mvc-4