28

我有以下 C# 类:

public class JsonBackup
{
    public int Added { set; get; }
    public int DEVCount { set; get; }
    public int DS1Count { set; get; }
    public IList<ViewEvent> Events { get; set; }
    public IEnumerable<string> Errors { set; get; }
    public int Rejected { set; get; }
    public bool Success { set; get; }
    public int Updated { set; get; }
}

这段代码将 JSON 数据返回到我的浏览器:

return Json(new JsonBackup
{
    Added = added,
    DEVCount = devCount,
    DS1Count = ds1Count,
    Events = t.Events,
    Rejected = rejected,
    Success = true,
    Updated = updated
});

数据在这里返回:

 $.ajax("/Backup/Data/Backup",
    {
        cache: false,
        dataType: 'json',
        type: 'POST'
    })
 .done(function (data: ) {
     console.log(data);
     backupDone(data, ajaxElapsed);
 });

并在其他地方使用,也在这里:

   $.each(data.Events, function (i, item) {
        $("#stats-list li:eq("+(4+i)+")").after('<li>' + item.Description + ' : ' + item.Elapsed + ' ms</li>');
    });

我是否可以创建一个 TypeScript 类型并将数据分配给该类型,这样我就可以在选择诸如此类的东西时获得智能感知

data.Added or data.DEVCount etc?
4

1 回答 1

52

实现这一目标的最简单方法是为 IJsonBackup 创建接口,当您收到 json 时,只需将其转换为 IJsonBackup

interface IViewEvent
{
}

interface IJsonBackup
{
    Added : number;
    DEVCount : number;
    DS1Count : number;
    Events : IViewEvent[];
    Errors : string[];
    Rejected : number;
    Success : bool;
    Updated : number;
}

在你的类定义中:

backupDone(data: IJsonBackup, ajaxElapsed: any)
{
}

$.ajax("/Backup/Data/Backup",
    {
        cache: false,
        dataType: 'json',
        type: 'POST'
    })
    .done(function (data: any) {
        console.log(data);
        backupDone(<IJsonBackup>data, ajaxElapsed);
    });
于 2012-11-10T09:20:00.860 回答