使用剃刀代码进行Razor Engine编译

时间:2018-01-16 10:14:46

标签: c# json razorengine

我正在使用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

1 个答案:

答案 0 :(得分: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并告诉您哪些位错误。