Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework ASP.NETMVC2.0在jqgrid中搜索的实现_Entity Framework_Asp.net Mvc 2_Search_Jqgrid_Linq To Entities - Fatal编程技术网

Entity framework ASP.NETMVC2.0在jqgrid中搜索的实现

Entity framework ASP.NETMVC2.0在jqgrid中搜索的实现,entity-framework,asp.net-mvc-2,search,jqgrid,linq-to-entities,Entity Framework,Asp.net Mvc 2,Search,Jqgrid,Linq To Entities,大家好,我正在尝试使用.NET(VS2008)中的MVC2在jqgrid中使用单列搜索。这是到目前为止我所拥有的代码,但我需要一个与之匹配的示例或我缺少的提示 jQuery("#list").jqGrid({ url: '/Home/DynamicGridData/', datatype: 'json', mtype: 'POST', search: true, filters: { "groupOp":"AND", "ru

大家好,我正在尝试使用.NET(VS2008)中的MVC2在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"
    }
}                              

});
有两件事没有提到 和搜索虽然我打开的搜索窗口中只有列1作为选项,当单击“查找”时,它似乎加载了网格,但实际上与我在文本框中键入的值不匹配

更新:如您所见,我尝试了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);
}
//public ActionResult DynamicGridData(string sidx、string sord、int page、int行、bool搜索、string fieldname、string fieldvalue)
公共操作结果DynamicGridData(字符串sidx、字符串sord、整型页面、整型行)
{
var context=new AlertsManagementDataContext();
int pageIndex=Convert.ToInt32(第页)-1;
int pageSize=行;
int totalRecords=context.Alerts.Count();
int totalPages=(int)数学上限((float)totalRecords/(float)pageSize);
IQueryable“+”|”+
" ",
alert.AlertId.ToString(),
alert.Policy.Name,
alert.PolicyRule,
alert.AlertStatus.Status,
alert.Code.ToString(),
警报,消息,
alert.Category.Name}
}).ToArray()
};
返回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', 'not equal','contains']
});
例如,描述了如何覆盖
emptyrecords
默认值。您不需要在默认jqGrid设置中包含已经相同的值

此外,如果对所有可搜索列使用
searchoptions:{sopt:['eq',ne',cn']}
,则无需进行更改

在问题的文本中,您没有解释您想要做什么。您当前的代码是这样的:在初始网格加载时,您可以使用过滤器
消息
等于
true
。奇怪的是,网格中没有名为
消息
的列。如果您想向服务器发送一些附加信息,您可以最好使用
postData
参数:

postData: {Message:true}
我继续建议您从jqGrid定义中删除垃圾,如jqGrid的
imgpath
multipleSearch
参数和
sortable:true、search:true、sorttype:'text',autoFit:true、stype:'text',align:'left'
,这些参数未知或默认

更新了:的原始代码非常旧,它使用LINQ to SQL。就像我之前写的(参见)实体框架(EF)允许使用排序、分页和过滤/搜索,而无需任何插件,如表单
System.LINQ.Dynamic
中的LINQ动态查询库。因此,我为您制作了一个演示,它是对to EF的修改

因为您使用的是旧版本的Visual Studio(带有ASP.NET MVC 2.0的VS2008),所以我也在VS2008中进行了演示

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

在我展示的代码中(除了在ASP.NET MVC 2.0中使用高级搜索和工具栏搜索),如何以JSON格式从ASP.NET MVC返回异常信息,以及如何使用该方法捕获信息并显示相应的错误消息

为了从表示的EF对象构造语句,我定义了以下帮助器类:

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

// 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;
        }
    }
}
//要将异常作为json发送,我们定义[HandleJsonException]属性
公共类例外信息{
公共字符串消息{get;set;}
公共字符串源{get;set;}
公共字符串StackTrace{get;set;}
}
公共类HandleJSoneExceptionAttribute:ActionFilterAttribute{
//下一个类示例是对
//http://www.dotnetcurry.com/ShowArticle.aspx?ID=496
公共覆盖无效OnActionExecuted(ActionExecutedContext筛选器上下文){
if(filterContext.HttpContext.Request.IsAjaxRequest()&&filterContext.Exception!=null){
filterContext.HttpContext.Response.StatusCode=
(int)System.Net.HttpStatusCode.InternalServerError;
var exInfo=新列表();
for(异常ex=filterContext.Exception;ex!=null;ex=ex.InnerException){
PropertyInfo PropertyInfo=ex.GetType().GetProperty(“错误代码”);
添加(新的例外信息(){
消息=例如消息,
来源=例如来源,
StackTrace=ex.StackTrace
});
}
filterContext.Result=newjsonresult(){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") %>',
    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(); }
            });
var myGrid=$('#list'),
decodeErrorMessage=函数(jqXHR、textStatus、ErrorSprown){
var html,errorInfo,即
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(); }
            });
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()
                  };
public JsonResult GetUsers(GridSettings gridSettings, string FirstName, string LastName)
{  
    // conditional logic and queries here and return results)
}