我有以下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?
答案 0 :(得分:40)
实现这一目标的最简单方法是为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);
});