这行得通! ..但还需要一件事...
好的,所以这既是“评论”又是问题。首先,是可以帮助其他人寻找 asp.net webmethod/jqGrid 方法的工作示例。下面的代码完全适用于从 jqGrid 发送/接收 JSON 参数,以便使用 LINQ 进行正确的分页、排序、过滤(仅限单次搜索)。它使用来自这里和那里的片段......
其次,我的问题是: 是否有人确定了一种适当的方法来说明发送到代码隐藏的动态运算符? 由于客户端可能会发送“eq”(等于),“cn”(包含)“gt”(大于) ,我需要一种更好的方法来动态生成 where 子句,它不仅限于使用“=”或“<>”构建 where 子句字符串,而是可以包含 Dynamic Linq 使用 .Contains 或 .EndsWith 的能力等。
我可能需要某种谓词构建器函数..
目前处理此问题的代码(有效,但受到限制):
if (isSearch) {
searchOper = getOperator(searchOper); // need to associate correct operator to value sent from jqGrid
string whereClause = String.Format("{0} {1} {2}", searchField, searchOper, "@" + searchField);
//--- associate value to field parameter
Dictionary<string, object> param = new Dictionary<string, object>();
param.Add("@" + searchField, searchString);
query = query.Where(whereClause, new object[1] { param });
}
继续表演…………
================================================ ===
<script type="text/javascript">
$(document).ready(function() {
var grid = $("#grid");
$("#grid").jqGrid({
// setup custom parameter names to pass to server
prmNames: {
search: "isSearch",
nd: null,
rows: "numRows",
page: "page",
sort: "sortField",
order: "sortOrder"
},
// add by default to avoid webmethod parameter conflicts
postData: { searchString: '', searchField: '', searchOper: '' },
// setup ajax call to webmethod
datatype: function(postdata) {
$(".loading").show(); // make sure we can see loader text
$.ajax({
url: 'PageName.aspx/getGridData',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postdata),
dataType: "json",
success: function(data, st) {
if (st == "success") {
var grid = $("#grid")[0];
grid.addJSONData(JSON.parse(data.d));
}
},
error: function() {
alert("Error with AJAX callback");
}
});
},
// this is what jqGrid is looking for in json callback
jsonReader: {
root: "rows",
page: "page",
total: "totalpages",
records: "totalrecords",
cell: "cell",
id: "id", //index of the column with the PK in it
userdata: "userdata",
repeatitems: true
},
colNames: ['Id', 'First Name', 'Last Name'],
colModel: [
{ name: 'id', index: 'id', width: 55, search: false },
{ name: 'fname', index: 'fname', width: 200, searchoptions: { sopt: ['eq', 'ne', 'cn']} },
{ name: 'lname', index: 'lname', width: 200, searchoptions: { sopt: ['eq', 'ne', 'cn']} }
],
rowNum: 10,
rowList: [10, 20, 30],
pager: jQuery("#pager"),
sortname: "fname",
sortorder: "asc",
viewrecords: true,
caption: "Grid Title Here",
gridComplete: function() {
$(".loading").hide();
}
}).jqGrid('navGrid', '#pager', { edit: false, add: false, del: false },
{}, // default settings for edit
{}, // add
{}, // delete
{ closeOnEscape: true, closeAfterSearch: true}, //search
{}
)
});
</script>
================================================ ===
[WebMethod]
public static string getGridData(int? numRows, int? page, string sortField, string sortOrder, bool isSearch, string searchField, string searchString, string searchOper) {
string result = null;
MyDataContext db = null;
try {
//--- retrieve the data
db = new MyDataContext("my connection string path");
var query = from u in db.TBL_USERs
select new User {
id = u.REF_ID,
lname = u.LAST_NAME,
fname = u.FIRST_NAME
};
//--- determine if this is a search filter
if (isSearch) {
searchOper = getOperator(searchOper); // need to associate correct operator to value sent from jqGrid
string whereClause = String.Format("{0} {1} {2}", searchField, searchOper, "@" + searchField);
//--- associate value to field parameter
Dictionary<string, object> param = new Dictionary<string, object>();
param.Add("@" + searchField, searchString);
query = query.Where(whereClause, new object[1] { param });
}
//--- setup calculations
int pageIndex = page ?? 1; //--- current page
int pageSize = numRows ?? 10; //--- number of rows to show per page
int totalRecords = query.Count(); //--- number of total items from query
int totalPages = (int)Math.Ceiling((decimal)totalRecords / (decimal)pageSize); //--- number of pages
//--- filter dataset for paging and sorting
IQueryable<User> orderedRecords = query.OrderBy(sortfield);
IEnumerable<User> sortedRecords = orderedRecords.ToList();
if (sortorder == "desc") sortedRecords= sortedRecords.Reverse();
sortedRecords = sortedRecords
.Skip((pageIndex - 1) * pageSize) //--- page the data
.Take(pageSize);
//--- format json
var jsonData = new {
totalpages = totalPages, //--- number of pages
page = pageIndex, //--- current page
totalrecords = totalRecords, //--- total items
rows = (
from row in sortedRecords
select new {
i = row.id,
cell = new string[] {
row.id.ToString(), row.fname, row.lname
}
}
).ToArray()
};
result = Newtonsoft.Json.JsonConvert.SerializeObject(jsonData);
} catch (Exception ex) {
Debug.WriteLine(ex);
} finally {
if (db != null) db.Dispose();
}
return result;
}
/* === User Object =========================== */
public class User {
public int id { get; set; }
public string lname { get; set; }
public string fname { get; set; }
}
================================================ ===
为了在 LINQ 中使用动态 OrderBy 子句,我必须将一个名为“Dynamic.cs”的类添加到我的 AppCode 文件夹中。您可以从 downloading here 检索文件。您将在“DynamicQuery”文件夹中找到该文件。该文件将使您能够使用动态 ORDERBY 子句,因为除了初始加载之外,我们不知道我们要过滤的列。
为了将 JSON 从 C-sharp 序列化回 JS,我合并了 James Newton-King JSON.net DLL: http://json.codeplex.com/releases/view/37810 。下载后,有一个“Newtonsoft.Json.Compact.dll”,您可以将其添加到您的 Bin 文件夹中作为引用
这是我的 USING block 使用系统; 使用 System.Collections; 使用 System.Collections.Generic; 使用 System.Linq; 使用 System.Web.UI.WebControls; 使用 System.Web.Services; 使用 System.Linq.Dynamic;
对于 Javascript 引用,我按相应顺序使用以下脚本,以防对某些人有所帮助:1) jquery-1.3.2.min.js ... 2) jquery-ui-1.7。 2.custom.min.js ... 3) json.min.js ... 4) i18n/grid.locale-en.js ... 5) jquery.jqGrid.min.js
对于 CSS,我使用 jqGrid 的必需品以及 jQuery UI 主题:1) jquery_theme/jquery-ui-1.7.2.custom.css ... 2) ui.jqgrid.css
无需在后端解析未序列化的字符串或不必设置一些 JS 逻辑来为不同数量的参数切换方法即可从 JS 获取参数到 WebMethod 的关键是这个 block
postData: { searchString: '', searchField: '', searchOper: '' },
当您实际进行搜索时,这些参数仍将正确设置,然后在您“重置”或希望网格不进行任何过滤时重置为空
希望这对其他人有所帮助!!!!感谢您有时间阅读并回复有关在运行时使用运算符构建 whereclause 的动态方法
最佳答案
考虑这种将字符串转换为 MemberExpression 的扩展方法:
public static class StringExtensions
{
public static MemberExpression ToMemberExpression(this string source, ParameterExpression p)
{
if (p == null)
throw new ArgumentNullException("p");
string[] properties = source.Split('.');
Expression expression = p;
Type type = p.Type;
foreach (var prop in properties)
{
var property = type.GetProperty(prop);
if (property == null)
throw new ArgumentException("Invalid expression", "source");
expression = Expression.MakeMemberAccess(expression, property);
type = property.PropertyType;
}
return (MemberExpression)expression;
}
}
以下方法将您拥有的字符串转换为 Lambda 表达式,您可以使用它来过滤 Linq 查询。它是一个泛型方法,以 T 为领域实体。
public virtual Expression<Func<T, bool>> CreateExpression<T>(string searchField, string searchString, string searchOper)
{
Expression exp = null;
var p = Expression.Parameter(typeof(T), "p");
try
{
Expression propertyAccess = searchField.ToExpression(p);
switch (searchOper)
{
case "bw":
exp = Expression.Call(propertyAccess, typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }), Expression.Constant(searchString));
break;
case "cn":
exp = Expression.Call(propertyAccess, typeof(string).GetMethod("Contains", new Type[] { typeof(string) }), Expression.Constant(searchString));
break;
case "ew":
exp = Expression.Call(propertyAccess, typeof(string).GetMethod("EndsWith", new Type[] { typeof(string) }), Expression.Constant(searchString));
break;
case "gt":
exp = Expression.GreaterThan(propertyAccess, Expression.Constant(searchString, propertyAccess.Type));
break;
case "ge":
exp = Expression.GreaterThanOrEqual(propertyAccess, Expression.Constant(searchString, propertyAccess.Type));
break;
case "lt":
exp = Expression.LessThan(propertyAccess, Expression.Constant(searchString, propertyAccess.Type));
break;
case "le":
exp = Expression.LessThanOrEqual(propertyAccess, Expression.Constant(searchString, propertyAccess.Type));
break;
case "eq":
exp = Expression.Equal(propertyAccess, Expression.Constant(searchString.ToType(propertyAccess.Type), propertyAccess.Type));
break;
case "ne":
exp = Expression.NotEqual(propertyAccess, Expression.Constant(searchString, propertyAccess.Type));
break;
default:
return null;
}
return (Expression<Func<T, bool>>)Expression.Lambda(exp, p);
}
catch
{
return null;
}
}
所以,你可以这样使用它:
db.TBL_USERs.Where(CreateExpression<TBL_USER>("LAST_NAME", "Costa", "eq"));
关于asp.net - jqgrid 与 asp.net webmethod 和 json 一起使用排序、分页、搜索和 LINQ——但需要动态运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2413032/
作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代
是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou
在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这
请帮助我理解范围运算符...和..之间的区别,作为Ruby中使用的“触发器”。这是PragmaticProgrammersguidetoRuby中的一个示例:a=(11..20).collect{|i|(i%4==0)..(i%3==0)?i:nil}返回:[nil,12,nil,nil,nil,16,17,18,nil,20]还有:a=(11..20).collect{|i|(i%4==0)...(i%3==0)?i:nil}返回:[nil,12,13,14,15,16,17,18,nil,20] 最佳答案 触发器(又名f/f)是
我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur
我有一个非常简单的RubyRack服务器,例如:app=Proc.newdo|env|req=Rack::Request.new(env).paramspreq.inspect[200,{'Content-Type'=>'text/plain'},['Somebody']]endRack::Handler::Thin.run(app,:Port=>4001,:threaded=>true)每当我使用JSON对象向服务器发送POSTHTTP请求时:{"session":{"accountId":String,"callId":String,"from":Object,"headers":
1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里
我正在使用ruby2.1.0我有一个json文件。例如:test.json{"item":[{"apple":1},{"banana":2}]}用YAML.load加载这个文件安全吗?YAML.load(File.read('test.json'))我正在尝试加载一个json或yaml格式的文件。 最佳答案 YAML可以加载JSONYAML.load('{"something":"test","other":4}')=>{"something"=>"test","other"=>4}JSON将无法加载YAML。JSON.load("
我明白了:x,(y,z)=1,*[2,3]x#=>1y#=>2z#=>nil我想知道为什么z的值为nil。 最佳答案 x,(y,z)=1,*[2,3]右侧的splat*是内联扩展的,所以它等同于:x,(y,z)=1,2,3左边带括号的列表被视为嵌套赋值,所以它等价于:x=1y,z=23被丢弃,而z被分配给nil。 关于ruby-带括号和splat运算符的并行赋值,我们在StackOverflow上找到一个类似的问题: https://stackoverflow
我很好奇.NET将如何影响Python和Ruby应用程序。用IronPython/IronRuby编写的应用程序是否会非常特定于.NET环境,以至于它们实际上将变得特定于平台?如果他们不使用任何.NET功能,那么IronPython/IronRuby相对于非.NET同类产品的优势是什么? 最佳答案 我不能说任何关于IronRuby的东西,但是大多数Python实现(如IronPython、Jython和PyPy)都试图尽可能忠实于CPython实现。不过,IronPython正在迅速成为这方面的佼佼者之一,并且在PlanetPyth