您的位置:首页 > 产品设计 > UI/UE

webapi返回泛型给easyui

2016-04-14 14:15 316 查看
由于之前遇到的easyui调用webapi的问题。

参见 :/article/9495115.html

所以就考虑,封装一个泛型用来返回 HttpResponseMessage

直接上代码:

泛型封装:

public class APIResult<T> : HttpResponseMessage
{
private T Data;

public APIResult(T Data, string DataType = "application/json")
{
this.Data = Data;
string jsonStr = GetJson(this.Data);
this.Content = new StringContent(jsonStr, System.Text.Encoding.UTF8, DataType);
}
//返回值
public bool ResponseResult = false;
//返回message
public string ResponseMsg = "failed";

private string GetJson(T Data)
{
if (Data is string || Data is StringBuilder)
return Data.ToString();
else if (Data is DataTable)
return JsonConvert.SerializeObject(Data, new DataTableConverter());
else
return JsonConvert.SerializeObject(Data);
}
}


webapi:

这里是返回DataTable类型

public APIResult<DataTable> GetProductParentType(string PT_Name=null, string PT_Code=null, int PT_ParentID = 0)
{
DataTable dt = pt.GetProductParentType(PT_Name, PT_Code,PT_ParentID);
APIResult<DataTable> result = new APIResult<DataTable>(dt);
return result;

}

这里是返回对象类型

public APIResult<Rootobject> Get(int id)
{
Rootobject resp=new Rootobject();
APIResult<Rootobject> api = new APIResult<Rootobject>(resp);

return api;
}


前台HTML :

<div id="gdv_ProductParentType"></div>

<script>

$('#gdv_ProductParentType').datagrid({
url: '../api/BindData/GetProductParentType',
method: 'get', //默认是post,不允许对静态文件访问
width: '700',
rownumbers: true,
columns: [[
{ field: 'PT_Name', title: 'PT_Name' },
{ field: 'PT_CreateTime', title: 'PT_CreateTime',
formatter: function (value, row, index) {
var dt = new Date(value);
return dt.toLocaleDateString();//设置时间格式
}
}
]],
onClickRow: function (index, row) {

},
singleSelect: true,
selectOnCheck: true
});

</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: