LINQ+Ajax动态查询怎么使用

发布时间:2021-12-01 15:58:01 作者:iii
来源:亿速云 阅读:111

本篇内容主要讲解“LINQ+Ajax动态查询怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“LINQ+Ajax动态查询怎么使用”吧!

思路:

1.前台发出请求 写明 调用的 modleName 和 一些属性 的过滤

如:Author like,1 ModelName Article   搜索作者 包含 1   对象名 文章

2.后台接受 处理传递的参数

3.根据 对象名 调用 对象 并过滤

4.根据 对象名 返回 对应 页面

1.前台JS 代码

前台代码

//===============//后台任一 类型  列表//========================function AjaxForList(duixiang, pageid) {      var searchWords = $("#SearchWords").val();      var searchType = $("#SearchType").val();      var channelId = $("#list").val();      var IsRecycle = $("#IsRecycle").attr("checked");    //排序名      var sortName = "CreaterData";      //==================IsRecycle    var Del = new Array();      Del.push("=");   //alert(IsRecycle);      if (IsRecycle) { Del.push(1);   }      else { Del.push(0); }      //==================FullTitle      // 2010-3-22 0:00:00    var FullTitle = new Array();      FullTitle.push("like");      FullTitle.push("1");      //==================FullTitle      var Author = new Array();      Author.push("like");      Author.push("1");      //==================IsAudit           var IsAudit = new Array();      IsAudit.push("=");      IsAudit.push("0");      //============================    $.ajax(//        {        type: "POST",        url: "/Admin/UserKJ/AjaxForList",       data: "ModelName=" + duixiang + "&&PageId=" + pageid + "&&sortName=" + sortName + "&&Del=" + Del + "&&FullTitle=" + FullTitle + "&&Author=" + Author + "&&IsAudit=" + IsAudit,        dataType: "html",        beforeSend: function(XMLHttpRequest) {   //            $(".PagerModeList").html(" ========LODING !!============");        },        success: function(html) {              //if (m != null)              //  alert(html);              $(".PagerModeList").html(html);                     },          complete: function(XMLHttpRequest, textStatus) {              //HideLoading();          },          error: function() {              //请求出错处理              $(".PagerModeList").html("加载失败");          }    }                                 )  //end $.ajax};   // end  AjaxRequest()   {
 

2后台接收:

使用 自定义的 两个 字典 合并成 一个 key-action-value 的字典

代码

public class SearchPage    {          public string ModelName { set; get; }          public int PageId { set; get; }          public string sortName { get; set; }          /// <summary>          /// RequestFormDictionary          /// </summary>          public ThreeDictionary<string, string, string> RFD = new ThreeDictionary<string, string, string>();        public SearchPage()          {              RFD = new ThreeDictionary<string, string, string>();          }          public void InitDictionary(System.Web.HttpRequestBase httpRequestBase)          {              var requestForm = httpRequestBase.Form;       foreach (var collection in requestForm.AllKeys)// x=     Article,0,,1,0,false  o=xx,xx;              {                  string actionAndvalue = requestForm.Get(collection);                  if (string.IsNullOrEmpty(collection)) continue;//把参数分离                    List<string> templist = actionAndvalue.splitString(',');                  if (templist.Count() < 2) continue;                RFD.Add(collection, templist[0], templist[1]);              }          }          public string Dictionary2SQL()          {            StringBuilder stringBuilder = new StringBuilder();              int count = 0;              foreach (var keyActon in RFD.keyActons)            {                  if (keyActon.Value == "Value") continue;   // @1特别指定 如果 是 动作是 Value  则 表示 直接意思                  string value = RFD.keyValues[keyActon.Key];                  if (count != 0) stringBuilder.Append(" and  ");                  count++;                  if (keyActon.Value == "like")                {                      //     continue;      //FullTitle.Contains(\"11\")                 stringBuilder.Append(string.Format(" {0}.Contains(\"{2}\") ", keyActon.Key, keyActon.Value, value));                  continue;                  }                  stringBuilder.Append(string.Format(" {0} {1} {2} ", keyActon.Key, keyActon.Value, value));              }              return stringBuilder.ToString();          }               }
 

3.根据 对象名 调用 对象 并过滤

代码

private readonly Repository2.IRepositoryResolver IRR;          public UserKJController()        {                          IRR = CMSContainer.GetContainer()[typeof(IRepositoryResolver)] as IRepositoryResolver;          }

这里用到了 一个 CASTLE  和 一个 Repository 相信 能看到这里的 应该都知道这些吧。

不知道的话 文末 会给出 链接。

AjaxForList

public ActionResult AjaxForList(SearchPage searchPage){//  Response.Write(DateTime.Now);searchPage.InitDictionary(Request);//把 字符串装进字典里面IRepository ir = IRR.GetRepository(searchPage.ModelName.str2type());  //根据类型得到要操作的类var iq = ir.GetAll();//   得到所有iq = iq.Order(searchPage.sortName);   //   并 排序iq = iq.Where(searchPage.Dictionary2SQL());//根据 字典 自动 过滤PagerInfo pif = new PagerInfo(iq.Count(), searchPage.PageId);  //页信息iq = iq.Skip(pif.PageSize * (pif.CurrentPage - 1)).Take(pif.PageSize);        //分页PagerIndex<PagerInfo, IQueryable>pagerIndex2 = new PagerIndex<PagerInfo, IQueryable>(pif, iq);//装配//Response.Write(DateTime.Now.ToLongTimeString());return View("AjaxListFor" + searchPage.ModelName, pagerIndex2);      //返回}

这里 用到了  System.Linq.Dynamic;

来做核心 的 排序和过滤 。

然后放出一个 firebug的 图

LINQ+Ajax动态查询怎么使用

通过我自己代码输出耗费的时间 不用1s 而且还是我本机的破机子,1G的内存条郁闷要死。

比我原来预想的 泛型会很耗性能。 感觉好了很多。

这是我没找到  Dynamic 之前 自己做的一个 轮子

辛辛苦苦做出来 还不支持 nullable的 类型 ,

想了办法 二次调用 构造 了 c.WithPic.Value的表达式

{Table(KF_Articles).OrderBy(ArticleID => ArticleID.ArticleID).Where(item => (item.Del =  0)).Where(item => (item.WithPic.Value = 1))}

结果

LINQ+Ajax动态查询怎么使用

跟重典兄讨论一下,还是没有结果。

等有时间再琢磨一下,希望 观众们 指点一下。

EqualValue我的轮子

//search/// <summary>/// 某个属性为某个值/// </summary>/// <param name="pif">属性</param>/// <param name="value">值</param>/// <param name="action">动作:    < = 等 </param>/// <returns></returns>public IQueryable EqualValue(string pifName, object value, ActionType action, IQueryable iq){if (iq == null) throw new Exception(" IQueryable iq  为空");if (typeof(T).GetProperty(pifName) == null)throw new Exception(pifName + "    in   " + typeof(T).Name);//1 构造 参数 item 即 Tvar itemParameter = Expression.Parameter(typeof(T), "item");IQueryable<T> iqTemp = iq as IQueryable<T>;// 转换成 model 的 那种类型// 判断是否是 Nullable 的  如果是 的话 就 把类型转换成对应的  非 nullable 的Type tempType = typeof(T).GetProperty(pifName).PropertyType;if (tempType.FullName.Contains("Nullable")){//组建一个表达式树来创建一个参数}var tempType2 = tempType.Nullable2Not();value = Convert.ChangeType(value, tempType2);//取出他的值var left = Expression.Property(// 左边的参数itemParameter,pifName // 属性的  名字);var right = Expression.Constant(value);//Constant 常量  右边的值#region   //=========================各种  action 操作BinaryExpression ep;if (action == ActionType.Equal){if (tempType.FullName.Contains("Nullable")){ParameterExpression param =Expression.Parameter(typeof(T), "item");//   item2//item2.pifName   =>    item2.WithPic//   item2.WithPic.valueMemberExpression param11 = Expression.Property(param, pifName);MemberExpression param12 = Expression.Property(param11, "Value");//      typeof(T).GetProperty(pifName).GetType().GetProperty("Value"));// ParameterExpression param2 =//Expression.Parameter(typeof(T).GetProperty(pifName).GetType(), "Value");//组建表达式树:c.ContactNameep = Expression.Equal(param12, right);}else{ep = Expression.Equal(left, right);}}else if (action == ActionType.GreaterThan){ep = Expression.GreaterThan(left, right);}else if (action == ActionType.GreaterThanOrEqual){ep = Expression.GreaterThanOrEqual(left, right);}else if (action == ActionType.LessThan){ep = Expression.LessThan(left, right);}else if (action == ActionType.LessThanOrEqual){ep = Expression.LessThanOrEqual(left, right);}else if (action == ActionType.NotEqual){ep = Expression.NotEqual(left, right);}else{throw new Exception(action + " not find!");}#endregionvar whereExpression = Expression.Lambda<Func<T, bool>>//构造表达式(ep, new[] { itemParameter });return iqTemp.Where(whereExpression);

指出 肖坤 兄的一处小错,Dynamic 也是支持 搜索的

//     continue;      FullTitle.Contains(\"11\")                    stringBuilder.Append(string.Format(" {0}.Contains(\"{2}\") ", keyActon.Key, keyActon.Value, value));

到此,相信大家对“LINQ+Ajax动态查询怎么使用”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. thinkphp 区间查询 组合查询 复合查询 动态查询 SQL查询
  2. 怎么在jQuery中使用Ajax动态执行模糊查询

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

linq ajax

上一篇:如何进行Python Profiling性能分析

下一篇:如何调用Servlet

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》