这有效! ..但还需要一件事...
好吧,这既是一个“评论”又是一个问题。首先,是可以帮助其他人寻找 asp.net webmethod / jqGrid 方法的工作示例。下面的代码完全适用于从 jqGrid 发送/接收 JSON 参数,以便利用 LINQ 进行正确的分页、排序、过滤(仅使用单个搜索)..它使用来自各处的片段...
其次,是我的问题:有没有人确定了一种适当的方法来计算发送到代码隐藏的动态运算符?由于客户端可能会发送“eq”(等于)、“cn”(包含)“gt”(大于),因此我需要一种更好的方法来动态生成一个 whereclause,而不仅仅限于我使用以下命令构建一个 whereclause 字符串“=”或“”,而是可以包含它以及 Dynamic Linq 使用 .Contains 或 .EndsWith 等的能力。
我可能需要某种谓词构建器函数..
目前处理此问题的代码(有效,但有限):
if (isSearch) {
searchOper = getOperator(searchOper); // need to associate correct operator to value sent from jqGrid
string whereClause = String.Format("{0} {1} {2}", searchField, searchOper, "@" + searchField);
//--- associate value to field parameter
Dictionary<string, object> param = new Dictionary<string, object>();
param.Add("@" + searchField, searchString);
query = query.Where(whereClause, new object[1] { param });
}
继续表演.......
===================================================
首先,JavaScript
<script type="text/javascript">
$(document).ready(function() {
var grid = $("#grid");
$("#grid").jqGrid({
// setup custom parameter names to pass to server
prmNames: {
search: "isSearch",
nd: null,
rows: "numRows",
page: "page",
sort: "sortField",
order: "sortOrder"
},
// add by default to avoid webmethod parameter conflicts
postData: { searchString: '', searchField: '', searchOper: '' },
// setup ajax call to webmethod
datatype: function(postdata) {
$(".loading").show(); // make sure we can see loader text
$.ajax({
url: 'PageName.aspx/getGridData',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postdata),
dataType: "json",
success: function(data, st) {
if (st == "success") {
var grid = $("#grid")[0];
grid.addJSONData(JSON.parse(data.d));
}
},
error: function() {
alert("Error with AJAX callback");
}
});
},
// this is what jqGrid is looking for in json callback
jsonReader: {
root: "rows",
page: "page",
total: "totalpages",
records: "totalrecords",
cell: "cell",
id: "id", //index of the column with the PK in it
userdata: "userdata",
repeatitems: true
},
colNames: ['Id', 'First Name', 'Last Name'],
colModel: [
{ name: 'id', index: 'id', width: 55, search: false },
{ name: 'fname', index: 'fname', width: 200, searchoptions: { sopt: ['eq', 'ne', 'cn']} },
{ name: 'lname', index: 'lname', width: 200, searchoptions: { sopt: ['eq', 'ne', 'cn']} }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: jQuery("#pager"),
sortname: "fname",
sortorder: "asc",
viewrecords: true,
caption: "Grid Title Here",
gridComplete: function() {
$(".loading").hide();
}
}).jqGrid('navGrid', '#pager', { edit: false, add: false, del: false },
{}, // default settings for edit
{}, // add
{}, // delete
{ closeOnEscape: true, closeAfterSearch: true}, //search
{}
)
});
</script>
===================================================
二、C# WEBMETHOD
[WebMethod]
public static string getGridData(int? numRows, int? page, string sortField, string sortOrder, bool isSearch, string searchField, string searchString, string searchOper) {
string result = null;
MyDataContext db = null;
try {
//--- retrieve the data
db = new MyDataContext("my connection string path");
var query = from u in db.TBL_USERs
select new User {
id = u.REF_ID,
lname = u.LAST_NAME,
fname = u.FIRST_NAME
};
//--- determine if this is a search filter
if (isSearch) {
searchOper = getOperator(searchOper); // need to associate correct operator to value sent from jqGrid
string whereClause = String.Format("{0} {1} {2}", searchField, searchOper, "@" + searchField);
//--- associate value to field parameter
Dictionary<string, object> param = new Dictionary<string, object>();
param.Add("@" + searchField, searchString);
query = query.Where(whereClause, new object[1] { param });
}
//--- setup calculations
int pageIndex = page ?? 1; //--- current page
int pageSize = numRows ?? 10; //--- number of rows to show per page
int totalRecords = query.Count(); //--- number of total items from query
int totalPages = (int)Math.Ceiling((decimal)totalRecords / (decimal)pageSize); //--- number of pages
//--- filter dataset for paging and sorting
IQueryable<User> orderedRecords = query.OrderBy(sortfield);
IEnumerable<User> sortedRecords = orderedRecords.ToList();
if (sortorder == "desc") sortedRecords= sortedRecords.Reverse();
sortedRecords = sortedRecords
.Skip((pageIndex - 1) * pageSize) //--- page the data
.Take(pageSize);
//--- format json
var jsonData = new {
totalpages = totalPages, //--- number of pages
page = pageIndex, //--- current page
totalrecords = totalRecords, //--- total items
rows = (
from row in sortedRecords
select new {
i = row.id,
cell = new string[] {
row.id.ToString(), row.fname, row.lname
}
}
).ToArray()
};
result = Newtonsoft.Json.JsonConvert.SerializeObject(jsonData);
} catch (Exception ex) {
Debug.WriteLine(ex);
} finally {
if (db != null) db.Dispose();
}
return result;
}
/* === User Object =========================== */
public class User {
public int id { get; set; }
public string lname { get; set; }
public string fname { get; set; }
}
===================================================
三、必需品
为了在 LINQ 中拥有动态 OrderBy 子句,我必须将一个名为“Dynamic.cs”的类拉入我的 AppCode 文件夹中。您可以从以下位置检索文件在这里下载 http://msdn.microsoft.com/en-us/vcsharp/bb894665.aspx。您将在“DynamicQuery”文件夹中找到该文件。该文件将使您能够利用动态 ORDERBY 子句,因为除了初始加载之外,我们不知道要过滤哪一列。
为了将 JSON 从升 C 序列化回 JS,我合并了此处找到的 James Newton-King JSON.net DLL:http://json.codeplex.com/releases/view/37810 http://json.codeplex.com/releases/view/37810。下载后,有一个“Newtonsoft.Json.Compact.dll”,您可以将其添加到您的Bin文件夹中作为参考
这是我的 USING 块
使用系统;
使用系统集合;
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Web.UI.WebControls;
使用 System.Web.Services;
使用 System.Linq.Dynamic;
对于 Javascript 参考,我按各自的顺序使用以下脚本,以防对某些人有所帮助:1) jquery-1.3.2.min.js ... 2) jquery-ui-1.7.2.custom.min。 js ... 3) json.min.js ... 4) i18n/grid.locale-en.js ... 5) jquery.jqGrid.min.js
对于 CSS,我使用 jqGrid 的必需品以及 jQuery UI 主题:1) jquery_theme/jquery-ui-1.7.2.custom.css ... 2) ui.jqgrid.css
从 JS 获取参数到 WebMethod 的关键在于这个块,而无需在后端解析未序列化的字符串或设置一些 JS 逻辑来切换不同数量参数的方法
postData: { searchString: '', searchField: '', searchOper: '' },
当您实际进行搜索时,这些参数仍然会正确设置,然后在您“重置”或希望网格不进行任何过滤时重置为空
希望这对其他人有帮助!!!!如果您有时间阅读并回复有关在运行时使用运算符构建 whereclause 的动态方法,谢谢