c# 后台封装 jqgrid 表头条件搜索
时间: 2023-07-25 20:31:37 浏览: 166
要在 C# 后台封装 jqGrid 表头条件搜索,你可以按照以下步骤进行:
1. 在后台定义一个方法,该方法接收 jqGrid 发送过来的搜索条件,并返回符合条件的数据列表,例如:
```
public List<MyModel> GetMyData(string sidx, string sord, int page, int rows, string filters)
{
// 解析搜索条件
JObject search = JObject.Parse(filters);
JArray rules = (JArray)search["rules"];
// 构造查询条件
string where = "";
foreach (JObject rule in rules)
{
string field = (string)rule["field"];
string op = (string)rule["op"];
string data = (string)rule["data"];
switch (op)
{
case "eq":
where += $" AND {field} = '{data}'";
break;
case "ne":
where += $" AND {field} <> '{data}'";
break;
case "lt":
where += $" AND {field} < '{data}'";
break;
case "le":
where += $" AND {field} <= '{data}'";
break;
case "gt":
where += $" AND {field} > '{data}'";
break;
case "ge":
where += $" AND {field} >= '{data}'";
break;
case "cn":
where += $" AND {field} LIKE '%{data}%'";
break;
}
}
// 查询数据并返回
List<MyModel> data = db.MyTable.Where($"1 = 1 {where}")
.OrderBy($"{sidx} {sord}")
.Skip((page - 1) * rows)
.Take(rows)
.ToList();
return data;
}
```
在上面的代码中,`sidx` 和 `sord` 参数表示排序字段和排序方式,`page` 和 `rows` 参数表示当前页码和每页显示的记录数,`filters` 参数表示搜索条件。该方法首先解析搜索条件,然后根据搜索条件构造查询条件,并使用 LINQ 查询数据并返回。
2. 在前端调用后台方法,并将搜索条件传递给后台,例如:
```
$("#grid").jqGrid({
url: "MyController/GetMyData",
postData: {
sidx: "id",
sord: "desc",
page: 1,
rows: 10,
filters: ""
},
datatype: "json",
colModel: [
{ name: "id", index: "id", width: 55 },
{ name: "name", index: "name", width: 90 },
{ name: "category", index: "category", width: 80, stype: "select", searchoptions: { value: ":All;1:Category 1;2:Category 2" } },
{ name: "price", index: "price", width: 80, align: "right", formatter: "currency", formatoptions: { decimalSeparator: ".", thousandsSeparator: ",", decimalPlaces: 2, prefix: "$ " }, searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge"] } },
],
rowNum: 10,
rowList: [10, 20, 30],
pager: "#pager",
sortname: "id",
viewrecords: true,
sortorder: "desc",
caption: "jqGrid Example",
height: "auto",
autowidth: true,
search: true,
searchOnEnter: false,
searchOperators: true,
searchToolbar: true,
onSearch: function () {
var postData = $("#grid").getGridParam("postData");
postData.filters = JSON.stringify($("#grid")[0].p.postData.filters);
$("#grid").setGridParam({ postData: postData }).trigger("reloadGrid");
},
});
```
在上面的代码中,`url` 属性指定后台方法的 URL,`postData` 属性指定传递给后台的参数,`onSearch` 事件在用户点击搜索按钮时触发,该事件将搜索条件转换为 JSON 字符串,并将其作为 `filters` 参数传递给后台方法。
通过以上步骤,你就可以在 C# 后台封装 jqGrid 表头条件搜索了。
阅读全文