Я создал JQGrid и успешно реализовал подкачку и сортировку на стороне сервера, а сейчас пытаюсь реализовать поиск на стороне сервера. Я потратил много времени на поиск в Интернете и нашел много примеров для MVC, в частности, от Олега, однако я не могу найти никаких не MVC примеров. ASP. NET MVC 2.0 Реализация поиска в jqgrid
Я также нашел этот пример для PHP, который выглядит как то, что мне нужно реализовать , но опять же я не уверен, как реализовать это в C# Двойном WHERE-запросе на стороне сервера для создания jqgrid json
С моим кодом мои параметры поиска пока отправлено обратно на мой WebMethod, например:
{"_search":true,"nd":1587555257753,"rows":5,"page":1,"sidx":"docid","sord":"asc","searchField":"","searchString":"","searchOper":"","filters":"{\"groupOp\":\"AND\",\"rules\":[{\"field\":\"docid\",\"op\":\"eq\",\"data\":\"888\"}]}"}
С чем я борюсь, это
- Фильтрую ли я свои данные с помощью кода позади?
- Делать Я передаю параметры поиска обратно на мой SQL сервер в виде оператора WHERE
Если опция b как мне транспонировать операторы JQGrid (например, "eq"), в что-то SQL может прочитайте "="?
Если бы кто-нибудь мог помочь с примером работающего кода для моего сценария, я был бы бесконечно благодарен!
Вот мой полный код для предоставления контактов
Мой JavaScript
function LoadGrid() {
jQuery("#jqquotes").jqGrid({
url: '../WebService1.asmx/getDataQuotes',
datatype: "json",
mtype: 'POST',
ajaxGridOptions: { contentType: "application/json" },
serializeGridData: function (postData) {
if (postData.searchField === undefined) postData.searchField = null;
if (postData.searchString === undefined) postData.searchString = null;
if (postData.searchOper === undefined) postData.searchOper = null;
if (postData.filters === undefined) postData.filters = null;
return JSON.stringify(postData);
},
jsonReader: {
root: function (obj) {
return typeof obj.d.rows === "string" ? $.parseJSON(obj.d.rows) : obj.d.rows;
},
page: function (obj) { return obj.d.page; },
total: function (obj) { return obj.d.total; },
records: function (obj) { return obj.d.records; },
repeatitems: false
},
loadComplete: function () {
//alert("OK");
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
},
onSelectRow: showDetailsGrid,
height: 'auto',
//autowidth: true,
rowNum: 5,
rowList: [5, 10, 15],
colNames: ['Doc ID', 'Quote #', 'Date', 'Customer'],
colModel: [
{ name: 'docid', key: true, index: 'docid', width: 55, editable: true },
{ name: 'quote_number', index: 'quote_number', width: 90, editable: true },
{
name: 'quote_date', formatter: 'date', datefmt: "d-m-Y", editoptions: { dataInit: initDateEdit },
formatoptions: { srcformat: "d/m/Y H:i:s", newformat: "d-m-Y" }, index: 'quote_date', width: 100, editable: true
},
{
name: 'cust_name', index: 'cust_name', width: 80, align: "left", editable: true, edittype: "select",
editoptions: {
value: {}
}
}
],
pager: "#jqquotesPager",
sortname: 'docid',
viewrecords: true,
caption: "Quotes",
gridview: true,
loadonce: false, //Important - Doesn't work without
}).navGrid('#jqquotesPager', { edit: true, add: true, del: true }, // options
{
url: '../WebService1.asmx/modifyDataQuotes',
closeAfterEdit: true,
beforeShowForm: function (form) {
$('#docid', form).attr("disabled", true);
},
ajaxEditOptions: { contentType: "application/json" },
recreateForm: true,
serializeEditData: function (postData) {
if (postData.exercise_value === undefined) { postData.exercise_value = null; }
return JSON.stringify(postData);
}
}, // edit options
{
url: "../WebService1.asmx/addDataQuotes",
closeAfterAdd: true,
beforeShowForm: function (form) {
$('#docid', form).attr("disabled", true);
},
ajaxEditOptions: { contentType: "application/json" },
recreateForm: true,
serializeEditData: function (postData) {
if (postData.exercise_value === undefined) { postData.exercise_value = null; }
return JSON.stringify(postData);
}
}, // add options
{
url: "../WebService1.asmx/deleteDataQuotes",
ajaxDelOptions: { contentType: "application/json" },
serializeDelData: function (postData) {
if (postData.exercise_value === undefined) { postData.exercise_value = null; }
return JSON.stringify(postData);
}
}, //del options
{
multipleSearch: true,
recreateFilter: true,
closeOnEscape: true,
overlay: false
}, // search options
);
}
Мой WebMethod
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public JqGridData getDataQuotes(bool _search, string nd, int rows, int page, string sidx, string sord, string filters)
{
//bool _search, string searchField, string searchOper, string searchString) {
//bool _search, string filters) {
// for advance search use "string filters" instead of last three parameters
// for simple search use "string searchField, string searchOper, string searchString"
if (_search && !string.IsNullOrEmpty(filters)) {
JavaScriptSerializer serializer = new JavaScriptSerializer();
jqGridSearchFilter searchFilter = serializer.Deserialize<jqGridSearchFilter>(filters);
}
string constr = ConfigurationManager.ConnectionStrings["Indigo2.Properties.Settings.Constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT [docid] ,[quote_number] ,[quote_date] ,c.[cust_name] FROM [Indigo].[dbo].[quotes] q LEFT JOIN [Indigo].[dbo].[customers] c on q.custid = c.custid ORDER BY " + sidx + " " + sord + " "))
{
cmd.Connection = con;
List<Quotes> quotes = new List<Quotes>();
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
quotes.Add(new Quotes
{
docid = sdr["docid"].ToString(),
quote_number = sdr["quote_number"].ToString(),
quote_date = sdr["quote_date"].ToString(),
cust_name = sdr["cust_name"].ToString()
});
}
}
int recordsCount = quotes.Count;
int startIndex = (page - 1) * rows;
int endIndex = (startIndex + rows < recordsCount) ? startIndex + rows : recordsCount;
List<Quotes> gridRows = new List<Quotes>(rows);
for (int i = startIndex; i < endIndex; i++)
gridRows.Add(quotes[i]);
con.Close();
return new JqGridData()
{
total = (recordsCount + rows - 1) / rows,
page = page,
records = recordsCount,
rows = gridRows
};
}
}
}