entity-framework – ASP.NET MVC 2.0在jqgrid中执行搜索

前端之家收集整理的这篇文章主要介绍了entity-framework – ASP.NET MVC 2.0在jqgrid中执行搜索前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
您好我试图使用单列搜索jqgrid使用MVC 2 IN .NET(VS 2008)这是我已经到目前为止的代码,但我需要一个示例来匹配它或一个我缺少的一个提示
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,sorttype: 'text',autoFit: true,stype:'text',searchoptions: { sopt: ['eq','ne','cn']} },{ name: 'column2',index: 'column2',search: false,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',{ 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"
    }
}                              

});

两个东西分页没有出来
搜索虽然我有搜索窗口打开只有hte column1作为选项,当单击查找它似乎它加载网格,但实际上没有匹配我的值,我在文本框中键入。

UPDATED:正如你可以看到我做了一个尝试与serach的参数,没有成功感谢你的帮助,感谢

//public ActionResult DynamicGridData(string sidx,string sord,int page,int rows,bool search,string fieldname,string fieldvalue)
public ActionResult DynamicGridData(string sidx,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);
}

解决方法

可能你在服务器端有问题。您可以将您的问题附加到您当前使用的DynamicGridData操作的代码。操作应该有过滤器作为参数。

当前代码的某些部分是明确错误的。例如jqGrid是jQuery插件。所以jQuery的方法将扩展与主要jqGrid方法,你使用作为jQuery(“#list”)。jqGrid(…)。所以在初始化jqGrid jQuery(“#list”)之后,jqGrid将是一个函数。在你的代码(最后一个语句)中,用对象{search:{…}}覆盖jQuery(“#list”)。jqGrid方法。你应该做什么,而不是

jQuery.extend(jQuery.jgrid.search,{
    odata : ['equal','contains']
});

像例如here描述如何覆盖emptyrecords的默认值。您不需要包括在默认jqGrid设置中已经相同的值。

此外,如果在所有可搜索的列上使用搜索选项:{sopt:[‘eq’,’ne’,’cn’]},则不需要进行更改。

在你的问题的文本中,你没有解释你想做什么。您当前的代码是这样的,使您在初始网格加载时使用过滤器等于true的消息。奇怪的是,在网格中没有名称为消息的列。如果你想只是发送一些额外的信息到服务器,你应该更好地使用postData参数:

postData: {Message:true}

我继续建议你从jqGrid定义中删除垃圾,像imgpath和multipleque的jqGrid参数和sortable:true,search:true,sorttype:’text’,autoFit:true,stype:’text’,align:’left’which是未知或默认值。

更新:the Phil Haack demo的原始代码非常旧,它使用LINQ to sql。像我之前写的(见here)实体框架(EF)允许使用排序,分页和过滤/搜索没有任何AddOns像LINQ动态查询库在形式System.Linq.Dynamic。所以我做演示你是你的the Phil Haack demo到EF的修改

因为你使用旧版本的Visual Studio(VS2008与ASP.NET MVC 2.0)我做的演示也在VS2008。

您可以从here和VS2010演示here下载我的VS2008演示。

代码中(除了在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;
    }
}

在示例中,我只使用两个数据类型整数(Edm.Int32)和字符串(Edm.String)。您可以轻松地展开示例,以根据上述属性信息.PropertyType.FullName值使用更多类型。

向jqGrid提供数据的控制器操作将非常简单:

public JsonResult DynamicGridData(string sidx,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,rows = (from item in queryDetails
                            select new[] {
                                item.Id.ToString(),item.Votes.ToString(),item.Title
                            }).ToList()
                });
}

要将异常信息以JSON形式发送到jqGrid,我将控制器(HomeController)的标准[HandleError]属性替换为[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;
        }
    }
}

在客户端我使用以下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") %>',colNames: ['Id','Votes','Title'],colModel: [
        { name: 'Id',index: 'Id',key: true,width: 40,'lt','le','gt','ge'] }
        },{ name: 'Votes',index: 'Votes',{ name: 'Title',index: 'Title',width: 400,searchoptions: { sopt: ['cn','nc','bw','bn','eq','ew','en','ge'] }
        }
    ],pager: '#pager',rowList: [5,10,20,50],sortname: 'Id',sortorder: 'desc',altRows: true,altclass: 'myAltRowClass',height: '100%',jsonReader: { cell: "" },caption: 'My first grid',loadError: function(jqXHR,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,errorThrown) + '</span></div><div style="clear:left"/></div>')
    },loadComplete: function() {
        // remove error div if exist
        $('#' + this.id + '_err').remove();
    }
});
myGrid.jqGrid('navGrid',{ add: false,del: false },overlay: false });
myGrid.jqGrid('filterToolbar',{ stringResult: true,searchOnEnter: true,defaultSearch: 'cn' });
myGrid.jqGrid('navButtonAdd',{ caption: "Filter",title: "Toggle Searching Toolbar",onClickButton: function() { myGrid[0].toggleToolbar(); }
            });

因此,如果在搜索工具栏中键入任何非数字文本(如“ttt”),则接收控制器操作代码(在Int32.Parse(rule.data)中)。一个客户端将会看到以下消息:

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

在现实世界中,验证用户输入和抛出异常与面向应用程序的错误消息。我在演示中使用的没有这样的验证显示所有种类的异常将被缓存和显示由jqGrid。

更新2:在the answer你会发现修改的VS2010演示(可从here下载),演示了jQuery UI Autocomplete的用法Another answer扩展代码以导出包含Excel格式的网格。

猜你在找的asp.Net相关文章