如何创建具有序列化到动态json对象的能力的c#类(例如datatables.net config)?

时间:2019-05-24 04:43:43

标签: c# json serialization datatables json.net

我正在将datatables.net用于ASP.NET MVC,我想创建一个包含Datatables.net所有属性的类名称DataTablesConfiguration。这样做的目的是在View或JS文件中配置数据表的属性,我可以通过在服务器端代码中设置DataTablesConfiguration对象的属性进行配置,然后将该对象序列化为json对象并传递到View中。因此,所有数据表的配置都将在服务器端完成。

示例:

我可以这样做来配置数据表:

    DataTablesConfiguration config = new DataTablesConfiguration();
    config.ServerSide = true;
    config.Ajax.Url = "/Demo/LoadData";
    config.Columns.Add(new DataTablesColumn
            {
                Data = "CustomerID",
                AutoWidth = true,
                Header= "CustomerID",
                Name = "CustomerID"
            });

问题是: 数据表具有许多具有动态类型的属性。例: 自动填充: 也许是这样:

$('#myTable').DataTable( {
    autoFill: true
} );

但有时:

$('#myTable').DataTable( {
    autoFill: {
        alwaysAsk: true,
        columns: ':not(:last-child)'
    }
} );
And sometimes:
$('#myTable').DataTable( {
    autoFill: {
        alwaysAsk: true,
        columns: [0,1,2],
        enable: true
    }
} );

按钮: 也许是这样:

$('#myTable').DataTable( {
    buttons: [
        'copy', 'excel', 'pdf'
    ]
} );

但是有一段时间:

$('#myTable').DataTable( {
    buttons: [
        {
            extend: 'copy',
            text: '<u>C</u>opy',
            key: {
                key: 'c',
                altKey: true
            },
            //and some other properties may appear here based on extend 
 property
        }
    ]
} );

我的意思是数据表配置中的属性是动态的。因此,如何使用C#代码按类描述它们,然后能够将其序列化为数据表确切想要接收的数据。 我尝试过:

public class DataTablesConfiguration
    {
        //Init default values base on datatables.net's reference
        public DataTablesConfiguration()
        {
            this.Buttons = new List<ButtonOption>();
        }

        [JsonProperty(PropertyName = "buttons")]
        public ICollection<ButtonOption> Buttons { get; set; }

        public string GetJsonConfig()
        {
            return JsonConvert.SerializeObject(this);
        }
    }

public class ButtonOption
    {
        public ButtonOption(string extend, string text)
        {
            this.Extend = extend;
            this.Text = text;
        }

        [JsonProperty(PropertyName = "extend")]
        public string Extend { get; set; }

        [JsonProperty(PropertyName = "text")]
        public string Text { get; set; }

        //How can I define all other properties here
    }

但这似乎不是一个好方法。有没有更好的方法可以使数据表可以在服务器端代码上配置?

0 个答案:

没有答案