0

我有一个使用dotliquid的 .NET Core 应用程序。从在线尝试看来,我可以绑定数组内对象的属性。就像{{user.tasks[0].name}}wheretaskstask对象的集合并且nametask.

我有 JSON 模型,可以作为模板的输入。我在设计时不知道 JSON 结构。所以我将 JSON 字符串转换为ExpandoObject.

但是,当我绑定数组内的对象的属性时,这不起作用。

演示 NETFiddle

public class Program
{
    public static void Main()
    {   
        // this does not work       
        var modelString = "{\"States\": [{\"Name\": \"Texas\",\"Code\": \"TX\"}, {\"Name\": \"New York\",\"Code\": \"NY\"}]}";
        var template = "State Is:{{States[0].Name}}";   
        Render(modelString,template);
        
        //this works
        modelString = "{\"States\": [\"Texas\",\"New York\"]}";
        template = "State Is:{{States[0]}}";    
        Render(modelString,template);
    }
    
    private static void Render(string modelString, string template)
    {
        var model = JsonConvert.DeserializeObject<ExpandoObject>(modelString);
        var templateModel = Hash.FromDictionary(model);
        var html = Template.Parse(template).Render(templateModel);
        Console.WriteLine(html);    
    }
}
4

1 回答 1

0

您应该解析为Dictionary<string, IEnumerable<ExpandoObject>>但不是ExpandoObject

using System;
using DotLiquid;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.Dynamic;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        // this does not work when binding a property of an object that is inside collection and when use dictionary
        var modelString = "{\"States\": [{\"Name\": \"Texas\",\"Code\": \"TX\"}, {\"Name\": \"New York\",\"Code\": \"NY\"}]}";
        var template = "State Is:{{Name}}";


        RenderFromDictionary(modelString, template);
    }

    private static void RenderFromDictionary(string modelString, string template)
    {
        var Stats = JsonConvert.DeserializeObject<Dictionary<string, IEnumerable<ExpandoObject>>>(modelString);
        foreach (ExpandoObject expandoObject in Stats["States"])
        {
            var templateModel = Hash.FromDictionary(expandoObject);
            var html = Template.Parse(template).Render(templateModel);
            Console.WriteLine(html);
        }
    }
}

测试结果:

在此处输入图像描述

于 2021-02-04T07:12:04.893 回答