【问题标题】:Razor Engine compilation using razor code使用 razor 代码编译 Razor Engine
【发布时间】:2018-01-16 10:14:46
【问题描述】:

我正在使用 RazorEngine,我的代码如下所示,

 public class Program
{
    static void Main(string[] args)
    {
        string jsonCompany = "[{'CompanyID' : '1','Name' : 'Company1','DepartmentName' : 'D1','ModifiedDate' : '2005-06-01 00:00:00.000',},{'CompanyID' : '2','Name' : 'Company2','DepartmentName' : 'D2','ModifiedDate' : '2005-06-01 00:00:00.000',},{'CompanyID' : '1','Name' : 'Company3','DepartmentName' : 'D3','ModifiedDate' : '2005-06-01 00:00:00.000',}]";

        string jsonDept = "[{'DepartmentID' : '91','Name' : 'Executive84','GroupName' : 'Executive General and Administration','ModifiedDate' : '2005-06-01 00:00:00.000',},{'DepartmentID' : '92','Name' : 'Executive85','GroupName' : 'Executive General and Administration','ModifiedDate' : '2005-06-01 00:00:00.000',},{'DepartmentID' : '93','Name' : 'Executive86','GroupName' : 'Executive General and Administration','ModifiedDate' : '2005-06-01 00:00:00.000',}]";

        object dynJsonCmp = JsonConvert.DeserializeObject(jsonCompany);

        dynamic dynJsonDept = JsonConvert.DeserializeObject(jsonDept);

        List<Object> nestedData = new List<Object>((IEnumerable<Object>)dynJsonCmp);

        List<Object> nestedcmpData = new List<object>();

        var array = dynJsonCmp as JArray;

        foreach (var cmp in array)
        {
            nestedcmpData.Add(cmp["Name"]);
        }

        //string template = "@Model";
        string template = "@var cmpData = new JArray(); @foreach (var cmp in Model) { cmpData.Add(cmp[\"Name\"]); } ";
        //string template = " @{var nestedresult = from p in Model.Values<JObject>()group p by new{Id = p['CompanyID'],} into g select new{Id = g.Key.Id, depts = g.Select(t => new { name = t['DepartmentName'] })}; return nestedresult;}";            
        var result = Engine.Razor.RunCompile(template, "templateKey", null, array);
        //var result = Engine.Razor.RunCompile(template, "templateKey", null, dynJsonCmp);
    }

    static void Print(object value)
    {
        var array = value as JArray;
        if (array != null)
            Print(array);
        else
        {
            var obj = value as JObject;
            if (obj != null)
                Print(obj);
            else
            {
                var val = value as JValue;
                if (val != null)
                    Print(val.Value);
                else
                {
                    if (value == null)
                        Console.WriteLine("null");
                    else
                        Console.WriteLine(value.ToString());
                }
            }
        }
    }

    static void Print(JArray array)
    {
        Console.WriteLine("[");
        foreach (var obj in array.Values<JObject>())
            Print(obj);
        Console.WriteLine("]");
    }

    static void Print(JObject obj)
    {
        Console.WriteLine("{");
        foreach (var prop in obj.Properties())
        {
            Console.Write(prop.Name + ": ");
            Print(prop.Value);
        }
        Console.WriteLine("}");
    }
}

我无法得到结果,错误是说,

RazorEngine.Templating.TemplateCompilationException: 'Errors while compiling a Template.
Please try the following to solve the situation:
  * If the problem is about missing/invalid references or multiple defines either try to load 
    the missing references manually (in the compiling appdomain!) or
    Specify your references manually by providing your own IReferenceResolver implementation.
    See https://antaris.github.io/RazorEngine/ReferenceResolver.html for details.
    Currently all references have to be available as files!
  * If you get 'class' does not contain a definition for 'member': 
        try another modelType (for example 'null' to make the model dynamic).
        NOTE: You CANNOT use typeof(dynamic) to make the model dynamic!
    Or try to use static instead of anonymous/dynamic types.
More details about the error:
 - error: (26, 7) The name 'var' does not exist in the current context
     - error: (30, 60) The name 'cmpData' does not exist in the current context
Temporary files of the compilation can be found in (please delete the folder): C:\Users\admin\AppData\Local\Temp\RazorEngine_vf4meokh.w1x

【问题讨论】:

    标签: c# json razorengine


    【解决方案1】:

    您的模板包含无效的 Razor 代码。您拥有的这段代码经过格式化,如下所示:

    @var cmpData = new JArray(); 
    @foreach (var cmp in Model) 
    {
        cmpData.Add(cmp[\"Name\"]); 
    }
    

    注意第一行是错误的,需要用大括号@{ ... }括起来。这样做会更好:

    @{var cmpData = new JArray(); }
    @foreach (var cmp in Model) 
    {
        cmpData.Add(cmp[\"Name\"]); 
    }
    

    我强烈建议将 Razor 模板保存在文件中而不是字符串中。它们更容易维护,也更容易调试。将它们保存为*.cshtml 文件,Visual Studio 会为您提供 IntelliSense 并告诉您哪些位是错误的。

    【讨论】:

    • 我已经添加了这段代码,但给出了这样的错误,找不到类型或命名空间名称“JArray”(您是否缺少 using 指令或程序集引用?那么我该如何添加引用这个剃须刀代码?
    • 这是一个不同的错误,同样,如果你把它写在一个普通的 Razor 文件中,你会遇到同样的问题。您需要添加一个@using... 行,指定JArray 的完整命名空间,例如Newtonsoft.Json.Linq.JArray
    • 那么,它奏效了吗?如果是这样,请考虑将答案标记为已接受(如果它们对您有帮助)。我注意到您之前的回答都没有被接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 2013-02-18
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多