从WebAPI Controller返回JSON数据

Thi*_*ena 1 asp.net json jqgrid asp.net-web-api

我想从我的WebAPI控制器返回一些JSON数据,我希望返回的数据是这样的.

{"rows":[{"id":1,"cell":["1","amila","amila","False"]},{"id":2,"cell":["2","rakhitha","rakhitha","False"]},{"id":3,"cell":["3","Chathura","Chathura","False"]},{"id":4,"cell":["4","Geethaga","Geethaga","False"]}]}
Run Code Online (Sandbox Code Playgroud)

但是当我使用下面的代码时,

return new System.Web.Mvc.JsonResult()
        {
            Data = jsonData,
            JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
        };
Run Code Online (Sandbox Code Playgroud)

像这样返回数据.

{"Data":{"rows":[{"id":1,"cell":["1","amila","amila","False"]},{"id":2,"cell":["2","rakhitha","rakhitha","False"]},{"id":3,"cell":["3","Chathura","Chathura","False"]},{"id":4,"cell":["4","Geethaga","Geethaga","False"]}]},"JsonRequestBehavior":0}
Run Code Online (Sandbox Code Playgroud)

还有一个额外的JSON密钥作为"数据".我不想要那个参数,作为我的实现,我不能删除它到客户端后的"数据"部分.因为从服务器接收的数据直接用于填充jqGrid.代码如下.

$("#Grid1").jqGrid({
            url: 'api/matchingservicewebapi/GetUser',
            datatype: 'json',
            mtype: 'GET',
            colNames: ['', 'Name', 'FullName', 'IsActive'],
            colModel: [
                { name: 'Id', index: 'Id', width: 200 },
                { name: 'Name', index: 'Name', width: 300 },
                { name: 'FullName', index: 'FullName', width: 300 },
                { name: 'IsActive', index: 'IsActive', width: 300 }
            ],
            rowNum: 10,
            rowList: [10, 20, 30],
            pager: '#pager',
            sortname: 'Id',
            viewrecoreds: true,
            sortorder: "desc",
            imgpath: 'Themes/images'
    }).navGrid(pager, { edit: true, add: true, del: true, refresh: true, search: true });
Run Code Online (Sandbox Code Playgroud)

如何删除此"数据"部分?因为当返回的JSON中有这个"数据"键时,jqGrid无法将该数据填充到网格中.

我正在使用WebAPI Controller来返回此数据.但我尝试使用MVC3控制器,然后这个"数据"键不在返回的JSON中,并且数据成功填充到网格中.但我想使用WebAPI Controller.请帮忙解决这个问题.

先感谢您.

Mik*_*son 13

JsonResult是一个MVC概念.对于Web API,您的控制器可以简单地返回一个CLR对象,它将被序列化为JSON(假设客户端要求使用JSON).

您看到的结果是因为整个JsonResult对象被序列化为JSON.

要开始使用Web API,请参阅:http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

(或者您可以继续使用MVC控制器......您是否有特殊原因要使用Web API控制器?)