webapi返回泛型给easyui
由于之前遇到的easyui调用webapi的问题。
参见 :http://blog.csdn.net/hanjun0612/article/details/51144991
所以就考虑,封装一个泛型用来返回 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);
}
}
这里是返回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;
}
<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>