小编典典

排序不适用于Json Result,无法提供编码输出

json

我正在使用Json
Result来显示表,当我显示结果时它工作正常。现在,我想为其添加排序功能,因此我使用了canSort:true属性。但是现在,每当我单击表的标题进行排序时,我都会在浏览器中获得下面的编码字符串,似乎它也已排序,但是对它进行了某种编码,如下所示。

{"Data":"\u003ctable class=\"paramCustomDataTable\"\u003e\u003cthead\u003e\u003ctr class=\"customHead\"\u003e\u003cth scope=\"col\"\u003e\u003ca href=\"/Parameters/CustomData?id=7&sort=Name&sortdir=ASC\"\u003eName\u003c/a\u003e\u003c/th\u003e\u003cth scope=\"col\"\u003e\u003ca href=\"/Parameters/CustomData?id=7&sort=Value&sortdir=DESC\"\u003eDataValue\u003c/a\u003e\u003c/th\u003e\u003cth scope=\"col\"\u003eDelete\u003c/th\u003e\u003c/tr\u003e\u003c/thead\u003e\u003ctbody\u003e\u003ctr\u003e\u003ctd\u003eNewdata\u003c/td\u003e\u003ctd\u003e123456\u003c/td\u003e\u003ctd\u003e\u003ca href=\u0027delete/5\u0027\u003eDelete\u003c/a\u003e\u003c/td\u003e\u003c/tr\u003e\u003c/tbody\u003e\u003c/table\u003e"}

我知道下面的代码可能存在一些不一致之处,因为我不得不删除版权问题的实际列。


C# code
[CacheControl(HttpCacheability.NoCache), AcceptVerbs(HttpVerbs.Get)]
 public JsonResult GetMyData(int id)      {
            var result = _myRepository.GetmyDataWithId(id).ToList();
            var grid = new WebGrid(result, rowsPerPage: 5, canSort:true);
            var htmlString = grid.GetHtml(
                                          columns: grid.Columns(
                                              grid.Column("Name", "Name"),
                                              grid.Column("Value", "DataValue"),                                              
                                              ));
        return Json(new
        {
           Data = htmlString.ToHtmlString()
        }
        , JsonRequestBehavior.AllowGet);
    }

JavaScript代码

 $.getJSON('@Url.Action("GetMyData")', { id: 1 }, function (result) {
                var customDataList = $('#grid');
                customDataList.empty();
                customDataList.append(result.Data);
            });

阅读 344

收藏
2020-07-27

共1个答案

小编典典

在ASP MVC 4中,您可以进行下一个IQueryable支持

下一个很酷的功能是IQueryable支持。如果需要,您可以返回IQueryable,而不是从API操作返回“普通” IEnumerable对象。为什么?

记住我们使用ASP.NET
MVC应用程序实现分页和排序的时代。这可能是有原因的,但需要大量的手动工作。必须使用其他参数来扩展操作,代码必须尊重这些参数并返回我们需要的数据的确切部分。排序相同的故事。在Web
API中,它要简单得多。

将签名和返回类型更改为IQueryable。

public IQueryable<Product> Get()
{
    return _storage.AsQueryable();
}

现在,如果Web API看到这样的方法,它将允许使用开放数据协议(OData)查询字符串参数进行访问。OData支持以下查询:$ filter,$
orderby,$ skip,$ top。

现在,如果我执行请求:

**http://localhost:5589/api/products?$top=3**

我会收到3个顶级产品。或类似的东西,

**http://localhost:5589/api/products?$skip=2&$top=3**

我将跳过2并休息3。简而言之,有了IQueryable和4个OData查询参数,可以轻松完成需要更多时间的工作。

2020-07-27