Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/333.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/asp.net/33.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
C# jqGrid LINQ和匿名类型_C#_Asp.net_Ajax_Jqgrid_Webforms - Fatal编程技术网

C# jqGrid LINQ和匿名类型

C# jqGrid LINQ和匿名类型,c#,asp.net,ajax,jqgrid,webforms,C#,Asp.net,Ajax,Jqgrid,Webforms,jqGrid采用以下JSON格式: { "total": "5", "page": "2", "records": "55", "rows" : [ {"id" :"21", "cell" :["cell11", "cell12", "cell13"]}, {"id" :"22", "cell" :["cell21", "cell22", "cell23"]}, ... {"id" :"30", "cell" :["cell31", "c

jqGrid采用以下JSON格式:

{ 
  "total": "5", 
  "page": "2", 
  "records": "55",
  "rows" : [
    {"id" :"21", "cell" :["cell11", "cell12", "cell13"]},
    {"id" :"22", "cell" :["cell21", "cell22", "cell23"]},
      ...
    {"id" :"30", "cell" :["cell31", "cell32", "cell33"]},
  ]
}
我试图使一种方法尽可能可重用,以便通过AJAX将数据传递回jqGrid

var result = new
{
    total = (int) Math.Ceiling((double) totalCount/PageSize),
    page = PageIndex,
    records = totalCount,
    rows = data.Select((d, id) => new {id, cell = d.SerializeGridParameters()}).ToArray()
};
正如您所看到的,目前我没有额外的努力就添加了索引,但是我在字段数据方面遇到了问题

到目前为止,我通过使用一个界面来处理它:

public interface IGridParameterListable
{
    List<string> SerializeGridParameters();
}
公共接口IGridParameterListable
{
列出参数();
}
对于我的数据(这是一个
IEnumerable,其中T:IGridParameterListable
)。
问题是,我更希望有一个通用方法,它只是盲目地将对象属性值转换为
列表

听起来不太可爱,我知道,我愿意接受其他想法。

我希望尽可能避免在客户端和服务器端重复网格的数据结构。

这可能是一个更好的选择

public string SerializeQuery<T>(IQueryable<T> query, Func<T, List<string>> select)
{
    // stuff ...

    var result = new
    {
        total = (int)Math.Ceiling((double)totalCount / PageSize),
        page = PageIndex,
        records = totalCount,
        rows = data.Select((d, id) => new { id, cell = select(d) }).ToArray()
    };

    // stuff ...
}
公共字符串序列化查询(IQueryable查询,Func选择)
{
//东西。。。
var结果=新
{
总数=(整数)数学上限((两倍)总数/页面大小),
页面=页面索引,
记录=总计数,
rows=data.Select((d,id)=>new{id,cell=Select(d)}).ToArray()
};
//东西。。。
}
我消除了对接口的需要,并将转换转移到每个特定网格的查询实现。在本例中:

[WebMethod]
[ScriptMethod]
    public string GetData(GridSettings grid)
    {
        var query = new FakeComputersRepository().Computers();
        var response = grid.SerializeQuery(query, d => new List<string>
        {
            d.ID.ToString(),
            d.IsOnline.ToString(),
            d.Name,
            d.IP,
            d.User
        });

        return response;
    }
[WebMethod]
[脚本方法]
公共字符串GetData(网格设置网格)
{
var query=new FakeComputersRepository().Computers();
var response=grid.SerializeQuery(查询,d=>newlist
{
d、 ID.ToString(),
d、 IsOnline.ToString(),
d、 名字,
d、 知识产权,
d、 使用者
});
返回响应;
}
我想好一点。 还有其他的想法吗?这不是答案,只是一些源代码 如果有人想要我的ASP.NET WebForms jqGrid实现,鉴于它很难实现,我将在这里发布代码

首先,一些JSON类:

public class GridFilter
{
    public string groupOp { get; set; }
    public GridRule[] rules { get; set; }
}

public class GridRule
{
    public string field { get; set; }
    public string op { get; set; }
    public string data { get; set; }
}

public class GridSettings
{
    public bool IsSearch { get; set; }
    public int PageSize { get; set; }
    public int PageIndex { get; set; }
    public string SortColumn { get; set; }
    public string SortOrder { get; set; }

    public GridFilter Where { get; set; }
}
前端代码,我修改了一些,这样我就可以只使用一个参数,填充网格信息发布到服务。另外,我并不真正喜欢单过滤器,所以我只支持多过滤器模式(这在我看来绝对是更好的)


$(文档).ready(函数(){
$('#UsersGrid').jqGrid({
colNames:['ID','Online','Computer','IP','User'],
colModel:[
{名称:'ID',宽度:100,索引:'ID',搜索选项:{sopt:['eq',ne']},
{name:'IsOnline',宽度:100,索引:'IsOnline',搜索选项:{sopt:['eq','ne']},
{name:'name',index:'name',searchoptions:{sopt:['eq',ne',cn']},
{name:'IP',index:'IP',searchoptions:{sopt:['eq','ne','cn']},
{名称:'User',索引:'User',搜索选项:{sopt:['eq','ne','cn']}
],
jsonReader:{
root:function(json){return json.parse(json.d).rows;},
page:function(json){return json.parse(json.d).page;},
total:function(json){return json.parse(json.d).total;},
记录:函数(json){返回json.parse(json.d).records;}
},
serializeGridData:jqGridSettings,
描述:“Usuarios”,
空记述:“不允许使用任何其他文件”,
url:“/GridTest/GridTestService.asmx/GetData”,
ajaxGridOptions:{contentType:'application/json;charset=utf-8'},
数据类型:“json”,
mtype:“POST”,
身高:250,
rowNum:10,
行列表:[10,25,50],
行数:对,
自动宽度:正确,
寻呼机:“#用户呼叫寻呼机”
}).navGrid(“#UsersGridPager”,
{
刷新:是的,
加:错,,
编辑:false,
戴尔:错,
搜索:正确
},
{},
{},
{},
{
sopt:[“eq”、“ne”、“cn”],
多重搜索:对,
showQuery:true
}
);
函数jqGridSettings(p){
变量设置={
网格:{
页面索引:第页,
页面大小:p.rows,
i搜索:p.(u搜索),
SortColumn:p.sidx,
排序者:p.sord,
其中:jqGridFilters(p.filters)
}
};
返回JSON.stringify(设置);
}
函数jqGridFilters(json){
变量过滤器={};
如果(!json){
回来
}
如果(!json.length){
回来
}
var parsed=JSON.parse(JSON);
如果(!!解析的规则){
过滤器=已解析;
}
回流过滤器;
}
});
现在,对于实际实施。。。首先,我们需要两种LINQ扩展方法来对数据进行排序和排序。详情如下:

public static IQueryable<T> OrderBy<T>(this IQueryable<T> query, string sortColumn, string direction)
{
    if (string.IsNullOrEmpty(sortColumn))
        return query;

    string methodName = string.Format("OrderBy{0}",
        direction.ToLower() == "asc" ? "" : "descending");

    ParameterExpression parameter = Expression.Parameter(query.ElementType, "p");

    MemberExpression memberAccess = null;
    foreach (var property in sortColumn.Split('.'))
        memberAccess = MemberExpression.Property(memberAccess ?? (parameter as Expression), property);

    LambdaExpression orderByLambda = Expression.Lambda(memberAccess, parameter);

    MethodCallExpression result = Expression.Call(
              typeof(Queryable),
              methodName,
              new[] { query.ElementType, memberAccess.Type },
              query.Expression,
              Expression.Quote(orderByLambda));

    return query.Provider.CreateQuery<T>(result);
}

public static IQueryable<T> Where<T>(this IQueryable<T> query, string column, object value, string operation)
{
    if (string.IsNullOrEmpty(column))
        return query;

    ParameterExpression parameter = Expression.Parameter(query.ElementType, "p");

    MemberExpression memberAccess = null;
    foreach (var property in column.Split('.'))
        memberAccess = MemberExpression.Property
           (memberAccess ?? (parameter as Expression), property);

    //change param value type
    //necessary to getting bool from string
    ConstantExpression filter = Expression.Constant
        (
            Convert.ChangeType(value, memberAccess.Type)
        );

    //switch operation
    LambdaExpression lambda = null;
    switch (operation)
    {
        case "eq": // equal
            {
                lambda = Expression.Lambda(Expression.Equal(memberAccess, filter), parameter);
                break;
            }
        case "ne": // not equal
            {
                lambda = Expression.Lambda(Expression.NotEqual(memberAccess, filter), parameter);
                break;
            }
        case "cn": // contains
            {
                Expression condition = Expression.Call(memberAccess,
                                                       typeof (string).GetMethod("Contains"),
                                                       Expression.Constant(value.ToString()));
                lambda = Expression.Lambda(condition, parameter);
                break;
            }
    }

    var result = Expression.Call(
           typeof(Queryable), "Where",
           new[] { query.ElementType },
           query.Expression,
           lambda);

    return query.Provider.CreateQuery<T>(result);
}
public静态IQueryable OrderBy(此IQueryable查询,字符串sortColumn,字符串方向)
{
if(string.IsNullOrEmpty(sortColumn))
返回查询;
string methodName=string.Format(“OrderBy{0}”,
direction.ToLower()=“asc”?:“下行”);
ParameterExpression参数=Expression.parameter(query.ElementType,“p”);
MemberExpression memberAccess=null;
foreach(sortColumn.Split('.')中的var属性)
memberAccess=MemberExpression.Property(memberAccess???(参数作为表达式),Property);
LambdaExpression orderByLambda=Expression.Lambda(memberAccess,参数);
MethodCallExpression结果=表达式.Call(
类型(
public static IQueryable<T> OrderBy<T>(this IQueryable<T> query, string sortColumn, string direction)
{
    if (string.IsNullOrEmpty(sortColumn))
        return query;

    string methodName = string.Format("OrderBy{0}",
        direction.ToLower() == "asc" ? "" : "descending");

    ParameterExpression parameter = Expression.Parameter(query.ElementType, "p");

    MemberExpression memberAccess = null;
    foreach (var property in sortColumn.Split('.'))
        memberAccess = MemberExpression.Property(memberAccess ?? (parameter as Expression), property);

    LambdaExpression orderByLambda = Expression.Lambda(memberAccess, parameter);

    MethodCallExpression result = Expression.Call(
              typeof(Queryable),
              methodName,
              new[] { query.ElementType, memberAccess.Type },
              query.Expression,
              Expression.Quote(orderByLambda));

    return query.Provider.CreateQuery<T>(result);
}

public static IQueryable<T> Where<T>(this IQueryable<T> query, string column, object value, string operation)
{
    if (string.IsNullOrEmpty(column))
        return query;

    ParameterExpression parameter = Expression.Parameter(query.ElementType, "p");

    MemberExpression memberAccess = null;
    foreach (var property in column.Split('.'))
        memberAccess = MemberExpression.Property
           (memberAccess ?? (parameter as Expression), property);

    //change param value type
    //necessary to getting bool from string
    ConstantExpression filter = Expression.Constant
        (
            Convert.ChangeType(value, memberAccess.Type)
        );

    //switch operation
    LambdaExpression lambda = null;
    switch (operation)
    {
        case "eq": // equal
            {
                lambda = Expression.Lambda(Expression.Equal(memberAccess, filter), parameter);
                break;
            }
        case "ne": // not equal
            {
                lambda = Expression.Lambda(Expression.NotEqual(memberAccess, filter), parameter);
                break;
            }
        case "cn": // contains
            {
                Expression condition = Expression.Call(memberAccess,
                                                       typeof (string).GetMethod("Contains"),
                                                       Expression.Constant(value.ToString()));
                lambda = Expression.Lambda(condition, parameter);
                break;
            }
    }

    var result = Expression.Call(
           typeof(Queryable), "Where",
           new[] { query.ElementType },
           query.Expression,
           lambda);

    return query.Provider.CreateQuery<T>(result);
}
public string SerializeQuery<T>(IQueryable<T> query, Func<T, List<string>> select)
{
    //filtering
    if (IsSearch && Where.rules != null)
    {
        if (Where.groupOp == "AND") // TODO: INSENSITIVE EQUALS, Y un enum GridGroupOperation.And.Name()
        {
            foreach (var rule in Where.rules)
                query = query.Where(rule.field, rule.data, rule.op);
        }
        else if (Where.groupOp == "OR") // TODO: INSENSITIVE EQUALS, Y un enum GridGroupOperation.Or.Name()
        {
            var temp = (new List<T>()).AsQueryable();

            foreach (var rule in Where.rules)
            {
                var t = query.Where(rule.field, rule.data, rule.op);
                temp = temp.Concat(t);
            }

            //remove repeat records
            query = temp.Distinct();
        }
    }

    //sorting
    query = query.OrderBy(SortColumn, SortOrder);

    //count
    var totalCount = query.Count();

    //paging
    var data = query.Skip((PageIndex - 1) * PageSize).Take(PageSize);

    //convert to grid format
    var result = new
    {
        total = (int)Math.Ceiling((double)totalCount / PageSize),
        page = PageIndex,
        records = totalCount,
        rows = data.Select((d, id) => new { id, cell = select(d) }).ToArray()
    };

    return JsonConvert.SerializeObject(result);
}
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService]
public class GridTestService : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod]
    public string GetData(GridSettings grid)
    {
        var query = new FakeComputersRepository().Computers();
        var response = grid.SerializeQuery(query, d => new List<string>
        {
            d.ID.ToString(),
            d.IsOnline.ToString(),
            d.Name,
            d.IP,
            d.User
        });

        return response;
    }
}
public string SerializeQuery<T>(IQueryable<T> query, Func<T, List<string>> select, Func<T, List<int>> ids)
    {
        //filtering
        if (IsSearch && Where.rules != null)
        {
            if (Where.groupOp == "AND") // TODO: INSENSITIVE EQUALS, Y un enum GridGroupOperation.And.Name()
            {
                foreach (var rule in Where.rules)
                    query = query.Where(rule.field, rule.data, rule.op);
            }
            else if (Where.groupOp == "OR") // TODO: INSENSITIVE EQUALS, Y un enum GridGroupOperation.Or.Name()
            {
                var temp = (new List<T>()).AsQueryable();

                foreach (var rule in Where.rules)
                {
                    var t = query.Where(rule.field, rule.data, rule.op);
                    temp = temp.Concat(t);
                }

                //remove repeat records
                query = temp.Distinct();
            }
        }

        //sorting
        query = query.OrderBy(SortColumn, SortOrder);

        //count
        var totalCount = query.Count();

        //paging
        var data = query.Skip((PageIndex - 1) * PageSize).Take(PageSize);

        //convert to grid format
        var result = new
        {
            total = (int)Math.Ceiling((double)totalCount / PageSize),
            page = PageIndex,
            records = totalCount,
            rows = data.Select((d) => new { 
                id = ids(d),
                cell = select(d) 
            }).ToArray()
        };

        return JsonConvert.SerializeObject(result);
    }