在ASP.NET MVC客户端视图中使用jQuery和LINQ对jqGrid进行排序

在ASP.NET MVC客户端视图中使用jQuery和LINQ对jqGrid进行排序,jquery,asp.net-mvc,linq,jqgrid,Jquery,Asp.net Mvc,Linq,Jqgrid,我是一个jquerynoob,所以我肯定我错过了一些简单的东西 我已经让jqGrid处理了一个从LINQ到Entities操作创建JSON数据的操作。但当我在浏览器中单击列标题时,行不会排序。升序/降序指示器显示,但没有其他情况发生 母版页标题中包含必要的JavaScript和CSS链接: <script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script> <!-- CSS and

我是一个jquerynoob,所以我肯定我错过了一些简单的东西

我已经让jqGrid处理了一个从LINQ到Entities操作创建JSON数据的操作。但当我在浏览器中单击列标题时,行不会排序。升序/降序指示器显示,但没有其他情况发生

母版页标题中包含必要的JavaScript和CSS链接:

<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script> <!-- CSS and JavaScript files for jqGrid to display on Details pages --> <link rel="stylesheet" type="text/css" href="/scripts/jQuery/jqGrid-3.4.4/themes/green/grid.css" title="green" media="screen" /> <script src="/Scripts/jQuery/jqGrid-3.4.4/jquery.jqGrid.js" type="text/javascript"></script> <script src="/Scripts/jQuery/jqGrid-3.4.4/js/jqModal.js" type="text/javascript"></script> <script src="/Scripts/jQuery/jqGrid-3.4.4/js/jqDnR.js" type="text/javascript"></script> 这是我的初始化代码:

// jqGrid setup. $("#gridlist").jqGrid({ url: '/Contact/GridData', datatype: 'json', mtype: 'GET', colNames: ['ID', 'First Name', 'Last Name', 'Organization'], colModel: [ { name: 'id', index: 'id', width: 40, align: 'left', resizable: true }, { name: 'first_name', index: 'first_name', width: 200, align: 'left', resizable: true, sortable: true, sorttype: "text" }, { name: 'last_name', index: 'last_name', width: 200, align: 'left', resizable: true, sortable: true, sorttype: "text" }, { name: 'organization', index: 'organization', width: 300, align: 'left', resizable: true, sortable: true, sorttype: "text"}], pager: jQuery('#pager'), rowNum: 5, rowList: [5, 10, 20, 50], repeatitems: false, viewrecords: true, imgpath: '/scripts/jQuery/jqGrid-3.4.4/themes/green/images', caption: 'Contacts' }); //jqGrid设置。 $(“#网格列表”).jqGrid({ url:“/Contact/GridData”, 数据类型:“json”, mtype:'获取', colNames:['ID','First Name','Last Name','Organization'], colModel:[ {name:'id',index:'id',width:40,align:'left',resizeable:true}, {name:'first_name',index:'first_name',宽度:200,对齐:'left',可调整大小:true,可排序:true,排序类型:“text”}, {name:'last_name',index:'last_name',宽度:200,对齐:'left',可调整大小:true,可排序:true,排序类型:“text”}, {name:'organization',index:'organization',width:300,align:'left',reshable:true,sortable:true,sorttype:'text}], pager:jQuery(“#pager”), 行数:5, 行列表:[5,10,20,50], 重复项:false, viewrecords:是的, imgpath:“/scripts/jQuery/jqGrid-3.4.4/themes/green/images”, 描述:“联系人” }); 下面是HTML:

<h3>My Grid Data</h3> <table id="gridlist" class="scroll" cellpadding="0" cellspacing="0"> </table> <div id="pager" class="scroll" style="text-align:center;"> </div> 我的网格数据 为了完整起见,行动方法:

public ActionResult GridData() { var page = new { page = 1 }; IEnumerable contacts = _db.ContactSet; int i = 0; var rows = new object[contacts.Count()]; foreach (Contact contact in contacts) { rows[i] = new { id = contact.ID, cell = new[] { contact.ID.ToString(), contact.First_Name, contact.Last_Name, contact.Organization } }; i++; } var result = new JsonResult(); result.Data = new { page = 1, records = 2, rows, total = 1 }; return result; } 公共操作结果GridData() { var page=new{page=1}; IEnumerable contacts=_db.ContactSet; int i=0; var rows=新对象[contacts.Count()]; foreach(触点中的触点) { 行[i]=new{id=contact.id,cell=new[]{contact.id.ToString(),contact.First_Name,contact.Last_Name,contact.Organization}; i++; } var result=新的JsonResult(); result.Data=new{page=1,records=2,rows,total=1}; 返回结果; }
你知道我这里缺少什么明显的设置吗?

有两种基本的方法来处理这个问题。网格可以对数据本身进行排序。我不记得如何打开它,因为我从来没有使用过这个选项。通常,我处理的数据集太大,无法返回页面,因此我使用网格的分页功能。这需要在服务器上执行此排序,因为网格不会看到整个数据集

要在服务器上执行分页,请将sidx和sord(两个字符串)参数添加到操作中。sidx将是要排序的列的名称。sord将是方向,asc或desc

我有一个演示如何做到这一点(使用LINQ对象)。但将LINQ用于实体几乎是相同的;我在生产/非演示代码中使用LINQ to实体。下载演示解决方案并自行寻找

  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


呵呵。。。这是否意味着我知道编程:)

好的,我应该在我弄明白的时候发布这个,但我最终被其他任务缠住了。下面是我使用LINQtoEntities所做的工作,它是为报表实体实现的。 首先,加载带有默认搜索的jqGrid的代码很简单(一旦我发现我遗漏了什么):

加载默认搜索集的方法返回整个可用报告集的第一页:

/// /// 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 /// ///查询报表集以返回分页、排序的报表实体属性集,以响应来自视图的调用。 /// ///用于排序的列的名称。 ///排序的顺序(升序或降序)。 ///要返回到调用进程的页码。 ///要为页面返回的行数。 ///此ActionResult返回一个JSON结果,供jqGrid使用jQuery库使用。 ///jQuery需要一个链接jQuery.js脚本的脚本标记。 ///jqGrid需要指向以下脚本和样式表的样式表链接: /// ///jQuery/themes/base/ui.all.css ///jqGrid/themes/green/grid.css(或其他主题css文件) ///jqGrid/jquery.jqGrid.js ///jqGrid/grid.base.js ///jqGrid/js/jqModal.js ///jqGrid/js/jqDnR.js /// public ActionResult GetResultsL2E(字符串sidx、字符串sord、整型页面、整型行) { int pageIndex=Convert.ToInt32(第页)-1; int pageSize=行; int totalRecords=_db.ReportSet.Count(); int totalPages=(int)数学上限((float)totalRecords/(float)pageSize); int startRecord=页面索引*页面大小; List rowStrings=新列表(); //以固定顺序获取模型中的所有报告(用于比较)。 //var reports=来自_db.ReportSet中的项 //orderby item.Start\u日期,item.Title //选择新{item.ID,item.Title,item.Post_Date, //item.Start\u日期、item.End\u日期、item.Summary}; //以从jqGrid传递的动态顺序获取模型中的所有报告。 字符串orderBytext=“”; orderBytext=string.Format(“it.{0}{1}”,sidx,sord); var reports=\u db.ReportSet .OrderBy(orderBytext); List stringList=新列表(); int counter=reports.Count(); foreach(报告中的var报告) { var rowString=new { id=report.id, 单元格=新[]{ "", report.ID.ToString(), 报告,标题, report.Post_Date.ToShortDateString(), report.Start_Date.ToShortDateString(), report.End_Date.ToString(), report.Summary.ToString()} }; stringList.Add(rowString); } var rowsOut=新对象[计数器]; 对于(int i=0;i
后来,我添加了另一种方法来响应用户选择要排序的列,使用Albaharis的书C#中讨论的PredicateBuilder(简而言之,在上一节中)。我在MSDN上的一个问题中讨论了我的解决方案,我在

上遇到了与jqGrid框架相同的问题 /// /// 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
**jsonData.JsonRequestBehavior = JsonRequestBehavior.AllowGet;**
         return jsonData;