Sue*_*Sue 25 search linq-to-entities entity-framework jqgrid asp.net-mvc-2
嗨我正在尝试使用MVC 2 IN .NET(VS 2008)在jqgrid中使用单列搜索这是我到目前为止的代码,但我需要一个示例来匹配它或者我缺少的一个提示
jQuery("#list").jqGrid({
url: '/Home/DynamicGridData/',
datatype: 'json',
mtype: 'POST',
search: true,
filters: {
"groupOp":"AND",
"rules": [
{"field":"Message","op":"eq","data":"True"}
]
},
multipleSearch: false,
colNames: [ 'column1', 'column2'],
colModel: [
{ name: 'column1', index: 'column1', sortable: true, search: true,
sorttype: 'text', autoFit: true,stype:'text',
searchoptions: { sopt: ['eq', 'ne', 'cn']} },
{ name: 'column2', index: 'column2', sortable: true,search: false,
sorttype: 'text', align: 'left', autoFit: true}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [10, 60, 100],
scroll: true,
sortname: 'column2',
sortorder: 'asc',
gridview: true,
autowidth: true,
rownumbers: true,
viewrecords: true,
imgpath: '/scripts/themes/basic/images',
caption: 'my data grid'
});
jQuery("#list").jqGrid('navGrid', '#pager', {add: false, edit: false, del: false},
{}, {}, {}, { multipleSearch: true, overlay: false });
//jQuery("#list").jqGrid('filterToolbar', {stringResult:true, searchOnEnter:true});
jQuery("#list").jqGrid('navButtonAdd', '#pager',
{ caption: "Finding", title: "Toggle Search Bar",
buttonicon: 'ui-icon-pin-s',
onClickButton: function() { $("#list")[0].toggleToolbar() }
});
jQuery("#list").jqGrid = {
search : {
caption: "Search...",
Find: "Find",
Reset: "Reset",
odata : ['equal', 'not equal','contains'],
groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ],
matchText: " match",
rulesText: " rules"
}
}
});
Run Code Online (Sandbox Code Playgroud)
虽然我只有hte column1作为一个选项打开搜索窗口,然后单击查找它似乎加载网格但实际上没有匹配我在文本框中键入的值.
更新:你可以看到我尝试了没有成功的serach论证再次感谢你的帮助,感激不尽
//public ActionResult DynamicGridData(string sidx, string sord, int page, int rows,bool search, string fieldname,string fieldvalue)
public ActionResult DynamicGridData(string sidx, string sord, int page, int rows)
{
var context = new AlertsManagementDataContext();
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = context.Alerts.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
IQueryable<Alert> alerts = null;
try
{
//if (!search)
//{
alerts = context.Alerts.
OrderBy(sidx + " " + sord).
Skip(pageIndex * pageSize).
Take(pageSize);
//}
//else
//{
// alerts = context.Alerts.Where (fieldname +"='"+ fieldvalue +"'").
// Skip(pageIndex * pageSize).
// Take(pageSize);
//}
}
catch (ParseException ex)
{
Response.Write(ex.Position + " " + ex.Message + " " + ex.Data.ToString());
}
//var alerts =
// from a in context.Alerts
// orderby sidx ascending
// select a;
var jsonData = new {
total = totalPages,
page = page,
records = totalRecords,
rows = (
from alert in alerts
select new {
id = alert.AlertId,
cell = new string[] {
"<a href=Home/Edit/"+alert.AlertId +">Edit</a> " +"|"+
"<a href=Home/Details/"+alert.AlertId +">Detail</a> ",
alert.AlertId.ToString() ,
alert.Policy.Name ,
alert.PolicyRule ,
alert.AlertStatus.Status ,
alert.Code.ToString() ,
alert.Message ,
alert.Category.Name}
}).ToArray()
};
return Json(jsonData);
}
Run Code Online (Sandbox Code Playgroud)
Ole*_*leg 26
可能你在服务器端有问题.您是否可以DynamicGridData使用当前使用的操作代码附加您的问题.该操作应该具有filters参数.
您当前代码的某些部分确实是错误的.例如jqGrid是jQuery插件.因此jQuery的方法将jqGrid使用您使用的main 方法进行扩展jQuery("#list").jqGrid(...);.所以在初始化jqGrid之后jQuery("#list").jqGrid会有一个函数.在您的代码(最后一个语句)中,您jQuery("#list").jqGrid使用该对象覆盖该方法{ search: { ... } }.你应该做的是
jQuery.extend(jQuery.jgrid.search, {
odata : ['equal', 'not equal','contains']
});
Run Code Online (Sandbox Code Playgroud)
例如,这里描述了如何覆盖emptyrecords默认值.您不需要在默认的jqGrid设置中包含已经相同的值.
此外,如果您searchoptions: { sopt: ['eq', 'ne', 'cn']}在所有可搜索的列上使用,则无需进行更改.
在您的问题文本中,您没有解释您想要做什么.您当前的代码是在初始网格加载时使用Message等于的过滤器true.奇怪的是,Message网格中没有名称列.如果您只想向服务器发送一些其他信息,最好使用postData参数:
postData: {Message:true}
Run Code Online (Sandbox Code Playgroud)
我继续建议你从jqGrid的定义等清除垃圾imgpath和multipleSearch的jqGrid和参数sortable: true, search: true, sorttype: 'text', autoFit: true, stype:'text', align: 'left'哪些是未知或默认.
更新:Phil Haack演示的原始代码非常陈旧,它使用LINQ to SQL.就像我之前写的那样(参见这里)实体框架(EF)允许使用排序,分页和过滤/搜索,而不需要像LINQ Dynamic Query Library那样的任何AddOns System.Linq.Dynamic.所以我做了你的演示,这是对Phil的Phil Haack演示的修改.
因为您使用的是旧版本的Visual Studio(带有ASP.NET MVC 2.0的VS2008),所以我也在VS2008中进行了演示.
你可以从这里下载我的VS2008的演示在这里和VS2010演示这里.
在我展示的代码中(除了在ASP.NET MVC 2.0中使用高级搜索和工具栏搜索)如何以JSON格式从ASP.NET MVC返回异常信息以及如何使用loadError方法捕获信息并显示相应的错误信息.
要从ObjectQuery表示的EF对象构造Where语句,我定义了以下帮助器类:
public class Filters {
public enum GroupOp {
AND,
OR
}
public enum Operations {
eq, // "equal"
ne, // "not equal"
lt, // "less"
le, // "less or equal"
gt, // "greater"
ge, // "greater or equal"
bw, // "begins with"
bn, // "does not begin with"
//in, // "in"
//ni, // "not in"
ew, // "ends with"
en, // "does not end with"
cn, // "contains"
nc // "does not contain"
}
public class Rule {
public string field { get; set; }
public Operations op { get; set; }
public string data { get; set; }
}
public GroupOp groupOp { get; set; }
public List<Rule> rules { get; set; }
private static readonly string[] FormatMapping = {
"(it.{0} = @p{1})", // "eq" - equal
"(it.{0} <> @p{1})", // "ne" - not equal
"(it.{0} < @p{1})", // "lt" - less than
"(it.{0} <= @p{1})", // "le" - less than or equal to
"(it.{0} > @p{1})", // "gt" - greater than
"(it.{0} >= @p{1})", // "ge" - greater than or equal to
"(it.{0} LIKE (@p{1}+'%'))", // "bw" - begins with
"(it.{0} NOT LIKE (@p{1}+'%'))", // "bn" - does not begin with
"(it.{0} LIKE ('%'+@p{1}))", // "ew" - ends with
"(it.{0} NOT LIKE ('%'+@p{1}))", // "en" - does not end with
"(it.{0} LIKE ('%'+@p{1}+'%'))", // "cn" - contains
"(it.{0} NOT LIKE ('%'+@p{1}+'%'))" //" nc" - does not contain
};
internal ObjectQuery<T> FilterObjectSet<T> (ObjectQuery<T> inputQuery) where T : class {
if (rules.Count <= 0)
return inputQuery;
var sb = new StringBuilder();
var objParams = new List<ObjectParameter>(rules.Count);
foreach (Rule rule in rules) {
PropertyInfo propertyInfo = typeof (T).GetProperty (rule.field);
if (propertyInfo == null)
continue; // skip wrong entries
if (sb.Length != 0)
sb.Append(groupOp);
var iParam = objParams.Count;
sb.AppendFormat(FormatMapping[(int)rule.op], rule.field, iParam);
// TODO: Extend to other data types
objParams.Add(String.Compare(propertyInfo.PropertyType.FullName,
"System.Int32", StringComparison.Ordinal) == 0
? new ObjectParameter("p" + iParam, Int32.Parse(rule.data))
: new ObjectParameter("p" + iParam, rule.data));
}
ObjectQuery<T> filteredQuery = inputQuery.Where (sb.ToString ());
foreach (var objParam in objParams)
filteredQuery.Parameters.Add (objParam);
return filteredQuery;
}
}
Run Code Online (Sandbox Code Playgroud)
在示例中,我只使用两种数据类型integer(Edm.Int32)和string(Edm.String).您可以轻松扩展示例,以便根据propertyInfo.PropertyType.FullName值使用更多类型.
向jqGrid提供数据的控制器操作非常简单:
public JsonResult DynamicGridData(string sidx, string sord, int page, int rows, bool _search, string filters)
{
var context = new HaackOverflowEntities();
var serializer = new JavaScriptSerializer();
Filters f = (!_search || string.IsNullOrEmpty (filters)) ? null : serializer.Deserialize<Filters> (filters);
ObjectQuery<Question> filteredQuery =
(f == null ? context.Questions : f.FilterObjectSet (context.Questions));
filteredQuery.MergeOption = MergeOption.NoTracking; // we don't want to update the data
var totalRecords = filteredQuery.Count();
var pagedQuery = filteredQuery.Skip ("it." + sidx + " " + sord, "@skip",
new ObjectParameter ("skip", (page - 1) * rows))
.Top ("@limit", new ObjectParameter ("limit", rows));
// to be able to use ToString() below which is NOT exist in the LINQ to Entity
var queryDetails = (from item in pagedQuery
select new { item.Id, item.Votes, item.Title }).ToList();
return Json(new {
total = (totalRecords + rows - 1) / rows,
page,
records = totalRecords,
rows = (from item in queryDetails
select new[] {
item.Id.ToString(),
item.Votes.ToString(),
item.Title
}).ToList()
});
}
Run Code Online (Sandbox Code Playgroud)
要以JSON格式将异常信息发送到jqGrid,我[HandleError]将controller(HomeController)的标准属性替换为[HandleJsonException]我定义的以下内容:
// to send exceptions as json we define [HandleJsonException] attribute
public class ExceptionInformation {
public string Message { get; set; }
public string Source { get; set; }
public string StackTrace { get; set; }
}
public class HandleJsonExceptionAttribute : ActionFilterAttribute {
// next class example are modification of the example from
// the http://www.dotnetcurry.com/ShowArticle.aspx?ID=496
public override void OnActionExecuted(ActionExecutedContext filterContext) {
if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null) {
filterContext.HttpContext.Response.StatusCode =
(int)System.Net.HttpStatusCode.InternalServerError;
var exInfo = new List<ExceptionInformation>();
for (Exception ex = filterContext.Exception; ex != null; ex = ex.InnerException) {
PropertyInfo propertyInfo = ex.GetType().GetProperty ("ErrorCode");
exInfo.Add(new ExceptionInformation() {
Message = ex.Message,
Source = ex.Source,
StackTrace = ex.StackTrace
});
}
filterContext.Result = new JsonResult() {Data=exInfo};
filterContext.ExceptionHandled = true;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在客户端,我使用了以下JavaScript代码:
var myGrid = $('#list'),
decodeErrorMessage = function(jqXHR, textStatus, errorThrown) {
var html, errorInfo, i, errorText = textStatus + '\n' + errorThrown;
if (jqXHR.responseText.charAt(0) === '[') {
try {
errorInfo = $.parseJSON(jqXHR.responseText);
errorText = "";
for (i=0; i<errorInfo.length; i++) {
if (errorText.length !== 0) {
errorText += "<hr/>";
}
errorText += errorInfo[i].Source + ": " + errorInfo[i].Message;
}
}
catch (e) { }
} else {
html = /<body.*?>([\s\S]*)<\/body>/.exec(jqXHR.responseText);
if (html !== null && html.length > 1) {
errorText = html[1];
}
}
return errorText;
};
myGrid.jqGrid({
url: '<%= Url.Action("DynamicGridData") %>',
datatype: 'json',
mtype: 'POST',
colNames: ['Id', 'Votes', 'Title'],
colModel: [
{ name: 'Id', index: 'Id', key: true, width: 40,
searchoptions: { sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'] }
},
{ name: 'Votes', index: 'Votes', width: 40,
searchoptions: { sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'] }
},
{ name: 'Title', index: 'Title', width: 400,
searchoptions: { sopt: ['cn', 'nc', 'bw', 'bn', 'eq', 'ne', 'ew', 'en', 'lt', 'le', 'gt', 'ge'] }
}
],
pager: '#pager',
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: 'desc',
rownumbers: true,
viewrecords: true,
altRows: true,
altclass: 'myAltRowClass',
height: '100%',
jsonReader: { cell: "" },
caption: 'My first grid',
loadError: function(jqXHR, textStatus, errorThrown) {
// remove error div if exist
$('#' + this.id + '_err').remove();
// insert div with the error description before the grid
myGrid.closest('div.ui-jqgrid').before(
'<div id="' + this.id + '_err" style="max-width:'+this.style.width+
';"><div class="ui-state-error ui-corner-all" style="padding:0.7em;float:left;"><span class="ui-icon ui-icon-alert" style="float:left; margin-right: .3em;"></span><span style="clear:left">' +
decodeErrorMessage(jqXHR, textStatus, errorThrown) + '</span></div><div style="clear:left"/></div>')
},
loadComplete: function() {
// remove error div if exist
$('#' + this.id + '_err').remove();
}
});
myGrid.jqGrid('navGrid', '#pager', { add: false, edit: false, del: false },
{}, {}, {}, { multipleSearch: true, overlay: false });
myGrid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: 'cn' });
myGrid.jqGrid('navButtonAdd', '#pager',
{ caption: "Filter", title: "Toggle Searching Toolbar",
buttonicon: 'ui-icon-pin-s',
onClickButton: function() { myGrid[0].toggleToolbar(); }
});
Run Code Online (Sandbox Code Playgroud)
结果,如果在搜索工具栏中键入任何非数字文本(如"ttt"),则会收到控制器操作代码(in Int32.Parse(rule.data))的异常.客户端之一将看到以下消息:

我从控制器发送有关所有内部异常的信息到jqgrid.因此,例如,与SQL服务器连接的错误将如下所示

在现实世界中,验证用户输入并使用面向应用程序的错误消息抛出异常.我在演示中使用了特别没有这种验证来表明所有类型的异常将被缓存并由jqGrid显示.
更新2:在答案中,您将找到修改后的VS2010演示(可从此处下载),演示了jQuery UI自动完成的用法.另一个答案是扩展代码,以便以Excel格式导出网格包含.
| 归档时间: |
|
| 查看次数: |
25424 次 |
| 最近记录: |