【问题标题】:Issue using RazorEngine with a dynamic model composed using JSON.net使用带有使用 JSON.net 组成的动态模型的 RazorEngine 问题
【发布时间】: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


【解决方案1】:

您不能将JObjects 直接传递给RazorEngine,因为每当您为JObject 赋值时,它们都会存储为JValue 类型。当您尝试检索分配的值时,您也会得到JValue 而不是分配的值。

例如

dynamic person = new JObject();
person.Name = "Vijay";

Console.WriteLine(person.Name.GetType());

==> NewtonSoft.Json.Linq.JValue

【讨论】:

  • 这是我关于使用 JObject 问题的答案,但我找到了我在上面的评论中概述的替代解决方案。
猜你喜欢
  • 2013-07-07
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
  • 2020-10-18
  • 2012-05-03
  • 1970-01-01
  • 1970-01-01
  • 2021-01-21
相关资源
最近更新 更多