Сортировка jqGrid в ASP.NET клиентское представление MVC с jQuery и LINQ к объектам

Посмотрите Чистый код Роберта Мартина, который охватывает это (среди прочего)

5
задан Tim Rourke 29 May 2009 в 19:48
поделиться

3 ответа

Есть два основных способа справиться с этим. Сетка может сама сортировать данные. Не могу вспомнить, как это включить, потому что никогда не использую эту опцию. Как правило, я работаю с наборами данных, которые слишком велики для возврата на страницу, поэтому я использую функции разбиения по страницам сетки. Для этого требуется выполнить такую ​​сортировку на сервере, поскольку сетка не будет видеть весь набор данных.

Чтобы выполнить разбиение на страницы на сервере, добавьте аргументы sidx и sord (обе строки) к вашему действию. sidx будет именем столбца для сортировки. sord будет направлением, asc или desc.

У меня есть демонстрационный проект , в котором показано, как это сделать (с использованием LINQ to Objects). Но использование LINQ to Entities практически идентично; Я использую LINQ to Entities в своем производственном / недемонстрационном коде. Загрузите демонстрационное решение и посмотрите сами.

4
ответ дан 14 December 2019 в 08:59
поделиться

Хорошо, мне следовало опубликовать это, когда я понял это, но в итоге я увлекся другими задачами. Вот что я сделал для работы с LINQ to Entities, реализованной для объекта отчета. Во-первых, код для загрузки jqGrid с поиском по умолчанию был простым (как только я понял, что я упустил):


$(document).ready(function() {

    // Set up jqGrid for the report search results table.
    // This is displayed in a tab in the bottom section of the master page.
    $("#searchResultList").jqGrid({
        url: '/Report/GetResultsL2E/',
        datatype: 'json',
        mtype: 'GET',
        colNames: ['', 'ID', 'Title', 'Post_Date', 'Start_Date', 'End_Date', 'Summary'],
        colModel: [
          { name: 'act', index: 'act', width: 75, sortable: false },
          { name: 'ID', index: 'ID', width: 40, align: 'left', hidden: true },
          { name: 'Title', index: 'Title', width: 150, align: 'left' },
          { name: 'Post_Date', index: 'Post_Date', width: 80, align: 'left', formatter: 'date' },
          { name: 'Start_Date', index: 'Start_Date', width: 80, align: 'left', formatter: 'date' },
          { name: 'End_Date', index: 'End_Date', width: 80, align: 'left', formatter: 'date' },
          { name: 'Summary', index: 'Summary', width: 240, align: 'left' }
        ],
        pager: jQuery('#searchResultPager'),
        rowNum: 10,
        rowList: [5, 10, 20, 50],
        sortname: 'Title',
        sortorder: "asc",
        viewrecords: true,
        imgpath: '/Scripts/jqGrid/themes/green/images',
        caption: 'Report Search Results', 
        editurl: "/Report/Edit",
        scroll: true,
        height: 'auto',
        recordtext: ' Reports',
        pgtext: ' of ',
        multiselect: true, 
        multiboxonly: true, //adds check box column
        altRows: true,
        loadComplete: function() {
            var ids = jQuery("#searchResultList").getDataIDs();
            for (var i = 0; i ";
                se = "";
                ce = "";
                jQuery("#searchResultList").setRowData(ids[i], { act: be + se + ce })
            }
        }
    }).navGrid('#searchResultPager',
    { edit: false, add: false, del: false, search: false }, //options 
    {height: 280, reloadAfterSubmit: false }, // edit options 
    {height: 280, reloadAfterSubmit: false }, // add options 
    {reloadAfterSubmit: false }, // del options 
    {} // search options 
    );
});

Метод загрузки набора поиска по умолчанию возвращает первую страницу из общего набора доступных отчетов:

/// 
/// Query the ReportSet to return a paged, sorted set of Report entity properties in response to a call from a view.
/// 
/// The name of the column to use for sorting.
/// The order of the sort (ascending or descending).
/// The number of the page to return to the calling process.
/// The number of rows to return for the page.
/// This ActionResult returns a JSON result to be used by a jqGrid using the jQuery library.
/// jQuery requires a script tag linking the jQuery.js script.
/// jqGrid requires stylesheet links to the following scripts and stylesheets:
/// 
/// jQuery/themes/base/ui.all.css
/// jqGrid/themes/green/grid.css (or other theme CSS file)
/// jqGrid/jquery.jqGrid.js
/// jqGrid/grid.base.js
/// jqGrid/js/jqModal.js
/// jqGrid/js/jqDnR.js
/// 
public ActionResult GetResultsL2E(string sidx, string sord, int page, int rows)
{
    int pageIndex = Convert.ToInt32(page) - 1;
    int pageSize = rows;
    int totalRecords = _db.ReportSet.Count();
    int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
    int startRecord = pageIndex * pageSize;

    List rowStrings = new List();
    // Get all of the reports in the model in a fixed order (for comparison).
    //var reports = from item in _db.ReportSet
    //              orderby item.Start_Date, item.Title
    //              select new { item.ID, item.Title, item.Post_Date, 
    //              item.Start_Date, item.End_Date, item.Summary };
    // Get all of the reports in the model in a dynamic order passed from jqGrid.
    string orderBytext = "";
    orderBytext = string.Format("it.{0} {1}", sidx, sord);
    var reports = _db.ReportSet
                   .OrderBy(orderBytext);

    List stringList = new List();

    int counter = reports.Count();
    foreach (var report in reports)
    {
        var rowString = new
        {
            id = report.ID,
            cell = new[] {
                    "",
                    report.ID.ToString(),
                    report.Title,
                    report.Post_Date.ToShortDateString(),
                    report.Start_Date.ToShortDateString(),
                    report.End_Date.ToString(),
                    report.Summary.ToString()}
        };
        stringList.Add(rowString);
    }

    var rowsOut = new object[counter];
    for (int i = 0; i 

Позже я добавил еще один метод ответа на выбор пользователем столбцов для сортировки, используя PredicateBuilder, описанный в книге Альбахариса C # в двух словах в разделе Динамическое составление предикатов выражений . Я обсуждал свое решение этого вопроса в вопросе, который я начал на MSDN в PredicateBuilder не работает на вложенных предикатах с LINQ to Entities

1
ответ дан 14 December 2019 в 08:59
поделиться
  I think below example should do it. 2 important points make sure your sort column has "it" keyword as prefix. (thats for linq to know). second you load only the number of objects array element as the rows the query can read.

  var context = new HaackOverflowDataContext();

    int pageIndex = Convert.ToInt32(page) - 1;
    int pageSize = rows;
    int totalRecords = context.Question.Count();
    int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

    var questions = context.Question.OrderBy("it."+ sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);

    int i = 0;
    var rowsObj = new object[pageSize>totalRecords ?  totalRecords : pageSize];

    foreach (Question q in questions)
    {
        rowsObj[i] = new { id = q.Id, cell = new object[] { q.Id, q.Votes, q.Title } };
        i++;
    }

    var result = new JsonResult();
    result.Data = new
    {
        total = totalPages,
        page = page,
        records = totalRecords,
        rows = rowsObj
    };

    return result;

Спасибо Анудж Пандей www.anuj.co.in

he he ... Значит ли это, что я знаю программирование :)

2
ответ дан 14 December 2019 в 08:59
поделиться
Другие вопросы по тегам:

Похожие вопросы: