XCLNetSearch1.0(ASP.NET通用查询服务器控件)
来源:互联网 发布:真小人 伪君子知乎 编辑:程序博客网 时间:2024/06/02 05:11
在开发项目的过程中,我们通常会碰到很多需要查询的地方,特别是信息列表页面,要根据字段信息去查询列表,当需要查询的字段很多或者需要查询的页面很多的时候,我们总要反复地去做些事情,其实很累很累。不就是get或post提交表单进行查询嘛,还总要写隐藏域什么的,虽然简单,但量大!
因此,本控件就是为了解决上述问题而写的,这个版本是根据我之前写的一个版本修改而来的,以前写的是用户控件,现在做成了一个服务器控件,而且比以前版本更加灵活。仁者见仁,智者见智。若您对本控件有任何建议或意见,请留言哦。
下载地址:https://github.com/xucongli1989/XCLNetSearch/releases
项目地址:https://github.com/xucongli1989/XCLNetSearch
ASP.NET(c#)通用查询控件
程序名:XCLNetSearch(原名为CommonSearch)
程序版本:1.0.5057.20247
.net版本:3.5
功能说明:
本查询控件基于JS,提交Form,最终生成SQL中的条件语句,如"a=b or a=c and m like '%n%'"等
目前只支持SQL SERVER的语法规则
需要引用的插件如下
dynamicCon.js(http://blog.csdn.net/luoyeyu1989/article/details/7435001 )
jquery
My97DatePicker
更新日期:2013-11-05
访问此网址来获取最新:http://blog.csdn.net/luoyeyu1989/article/details/7909334
更新日志:
1、查询时可以选择不同的日期格式,如2013-11-01、2013-11等,使用方法new SearchFieldInfo("告警开始时间",string.Format("ACStartTime|dateTime{0}|text",(int)XCLNetSearch.Common.SearchDateFmt.yyyy_MM),"","yyyy-MM")
版本:1.0.0.0
更新日期:2012-08
下面来看看此控件到底做了什么:
控件原理很简单的,再看看主要代码哦:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Linq;using System.Text;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Text.RegularExpressions;namespace CommonSearch{ /// <summary> /// 查询控件主体(此控件基于JS) /// 需要引用外部JS:dynamicCon.js、jquery-1.5.2.min.js、My97DatePicker /// 原理:将条件拼接为SQL查询中的WHERE后面的条件语句。使用form提交表单 /// by:xcl @2012.8 qq:80213876 http://blog.csdn.net/luoyeyu1989 (如需修改此控件,请保留此行信息即可,谢谢) /// </summary> [ToolboxData("<{0}:Search runat=server></{0}:Search>")] public class Search : WebControl { private static string getGuid = "_" + Guid.NewGuid().ToString("N");//作为JS的全局变量名 private string _strParamName = "where"; private string _formType = "get"; private string selOptions = ""; private string selInputOptionsEventJs = "";//字段区change时执行响应输入区option的语句 private List<SearchFieldInfo> _typeList = null; private int _maxLine = 5; /// <summary> /// guid作为容器ID /// </summary> public string GetGuid { get { return getGuid + this.UniqueID.Replace('$', '_'); } } /// <summary> /// 初始化 /// </summary> protected void InitData() { #region 生成字段select的option StringBuilder strJs = new StringBuilder(); StringBuilder str = new StringBuilder("<option value=\"\" type=\"string\" inputType=\"text\">--重置此条件--</option>"); if (null != this.TypeList && this.TypeList.Count > 0) { string[] strFieldType = { }; foreach (SearchFieldInfo m in this.TypeList) { strFieldType = m.Value.Split('|'); if (strFieldType.Length == 3) { str.AppendFormat("<option value=\"{0}\" type=\"{1}\" inputType=\"{2}\">{3}</option>", strFieldType[0], strFieldType[1], strFieldType[2], m.Text); if (!string.IsNullOrEmpty(m.FieldChangedHtml)) { strJs.AppendFormat(@"case ""{0}"":selHtml=""{1}"";break;", strFieldType[0], m.FieldChangedHtml.Replace("\"","'")); } } } this.selOptions = str.ToString(); this.selInputOptionsEventJs = strJs.ToString(); } #endregion this.StrSQL = Common.GetSearchStrByUrl(this, this.StrParamValue); } /// <summary> /// 最多几行条件 /// </summary> public int MaxLine { get { return this._maxLine; } set { this._maxLine = value; } } /// <summary> /// 提交表单的方式(get,post) /// </summary> public string FormType { get { return this._formType; } set { this._formType = value; } } /// <summary> /// 此控件生成的查询后的参数名,也是隐藏hidden的name /// </summary> public string StrParamName { get { return this._strParamName; } set { this._strParamName = value; } } /// <summary> /// 此控件查询参数的值,也是隐藏hidden的value /// </summary> public string StrParamValue { get { if (string.Equals(this.FormType, "get", StringComparison.InvariantCultureIgnoreCase)) { return HttpContext.Current.Request.QueryString[this.StrParamName] ?? ""; } else { return HttpContext.Current.Request.Form[this.StrParamName] ?? ""; } } } /// <summary> /// 要查询的字段list(给此字段赋值时即进行此控件数据的初始化) /// </summary> public List<SearchFieldInfo> TypeList { get { return this._typeList; } set{ this._typeList=value; this.InitData(); } } /// <summary> /// 错误信息提示 /// </summary> public string strMsg { get; set; } /// <summary> /// 字段发生change事件时,输入区要替换的option(用于输入区类型为select时) /// </summary> public List<ListItem> FieldChangeList { get; set; } /// <summary> /// 最终拼接的SQL条件语句 /// </summary> public string StrSQL { get; set; } #region 所有控件的NAME属性 /// <summary> /// 左括号 /// </summary> public string LeftBracketName { get { return string.Format("{0}_leftBracket", this.GetGuid); } } /// <summary> /// 搜索的字段 /// </summary> public string SelSearchTypeName { get { return string.Format("{0}_selSearchType", this.GetGuid); } } /// <summary> /// 比较符号 /// </summary> public string SymbolName { get { return string.Format("{0}_symbol", this.GetGuid); } } /// <summary> /// 输入区 /// </summary> public string TxtSearchValueName { get { return string.Format("{0}_txtSearchValue", this.GetGuid); } } /// <summary> /// 右括号 /// </summary> public string RightBracketName { get { return string.Format("{0}_rightBracket", this.GetGuid); } } /// <summary> /// 逻辑符 /// </summary> public string LogicName { get { return string.Format("{0}_logic", this.GetGuid); } } #endregion /// <summary> /// (如需修改此控件,请保留此信息即可,谢谢) /// </summary> public override void RenderBeginTag(HtmlTextWriter writer) { writer.Write("<!--*****************by xcl @2012.8 http://blog.csdn.net/luoyeyu1989*****************-->"); base.RenderBeginTag(writer); } /// <summary> /// (如需修改此控件,请保留此信息即可,谢谢) /// </summary> public override void RenderEndTag(HtmlTextWriter writer) { writer.Write("<!--*****************by xcl @2012.8 http://blog.csdn.net/luoyeyu1989*****************-->"); base.RenderEndTag(writer); } /// <summary> /// 渲染html /// </summary> protected override void RenderContents(HtmlTextWriter output) { StringBuilder str = new StringBuilder(); str.AppendFormat(@"<table width=""100%"" border=""0"" cellspacing=""0"" cellpadding=""0"" class=""{0}""> <tr> <td align=""center""> <a href=""javascript:void(0);"" class=""openImg""><img src=""{21}"" border=""0"" alt=""展开搜索""/></a> <input type=""hidden"" IsSubmit=""1"" name=""{14}"" value=""{15}""/> </td> </tr> <tr> <td align=""center""> <div class=""divSearch""> <table border=""0"" cellspacing=""0"" cellpadding=""0""> <tr> <td> <table border=""0"" cellspacing=""0"" cellpadding=""0""> <tr class=""items""> <td align=""center"" style=""padding-top:3px;padding-bottom:3px""> <select name=""{1}""> <option value=""-1""></option> {2} </select> — <select name=""{3}""> {4} </select> — <select name=""{5}"" style=""width:80px;""> {6} </select> — <input type=""text"" name=""{7}"" style=""width:120px;""/> — <select name=""{8}""> <option value=""-1""></option> {9} </select> — <select name=""{10}""> {11} </select> </td> <td align=""left""> <a href=""javascript:void(0);"" class=""addBtn"" title=""增加搜索条件""><img src=""{17}"" border=""0"" /></a> <a href=""javascript:void(0);"" class=""delBtn"" title=""删除搜索条件""><img src=""{18}"" border=""0"" /></a> </td> </tr> <tr class=""temp""> <td align=""center"" style=""padding-top:3px;padding-bottom:3px""> <select name=""{1}""> <option value=""-1""></option> {2} </select> — <select name=""{3}""> {4} </select> — <select name=""{5}"" style=""width:80px;""> {6} </select> — <input type=""text"" name=""{7}"" style=""width:120px;""/> — <select name=""{8}""> <option value=""-1""></option> {9} </select> — <select name=""{10}""> {11} </select> </td> <td align=""left""> <a href=""javascript:void(0);"" class=""addBtn"" title=""增加搜索条件""><img src=""{17}"" border=""0"" /></a> <a href=""javascript:void(0);"" class=""delBtn"" title=""删除搜索条件""><img src=""{18}"" border=""0"" /></a> </td> </tr> </table> </td> <td align=""left"" style=""padding-left:10px;""> <a href=""###"" class=""btnSearch""><img src=""{19}"" border=""0"" /></a> {23} </td> </tr> </table> </div> </td> </tr> </table> <script src=""{22}"" type=""text/javascript""></script> <script type=""text/javascript""> $(function () {{ {0}.Init(); $("".{0}"").find(""select[name='{3}']"").live(""change"", function () {{ {12} }}); }}); var {0}={{ /*字段change时,若输入区为select,则响应*/ GetInputOption:function(obj){{ $inputObj = $(obj).closest(""tr"").find(""[name='{7}']""); /*要输入的地方*/ var selHtml = """"; switch (obj.value) {{ {25} }}; if (selHtml != """") {{ $inputObj.html(selHtml); }} }}, /*字段Change事件*/ FieldChange:function(obj){{ var typeValue = $.trim($(obj).find(""option:selected"").attr(""type"")); /*字段的类型*/ var inputType=$.trim($(obj).find(""option:selected"").attr(""inputType"")); /*要输入的控件类型(select 、input。。。)*/ $txtInput = $(obj).closest(""tr"").find(""[name='{7}']"");/*手动输入区(更新控件类型前)*/ /*设置手动输入区的控件类型*/ switch(inputType) {{ case ""text"": $txtInput.after(""<input type=\""text\"" name=\""{7}\"" style=\""width:120px;\""/>""); $txtInput.remove(); break; case ""select"": $txtInput.after(""<select name=\""{7}\"" style=\""width:120px;\""/></select>""); $txtInput.remove(); break; }} $txtInput = $(obj).closest(""tr"").find(""[name='{7}']"");/*手动输入区(更新控件类型后)*/ $txtInput.removeAttr(""readonly"").unbind(""click""); $symbolObj=$(obj).closest(""tr"").find(""[name='{5}']"");/*符号*/ $symbolObj.html('{6}'); switch (typeValue) {{ case ""dateTime"": $symbolObj.find(""option[value='{13}']"").remove();/*去掉like*/ $txtInput.bind(""click"",function(){{ WdatePicker({{dateFmt:'yyyy-MM-dd',readOnly:true}}); }}); break; case ""ntext"":/*ntext只能使用is null和like,不能使用比较符*/ $symbolObj.find(""option[value!='{13}']"").remove(); break; case ""number"":/*数字把like去掉(不去掉sql也不报错)*/ $symbolObj.find(""option[value='{13}']"").remove(); break; }} }}, Init:function(){{ $con = $(""table.{0}""); $searchCon = $con.find("".divSearch""); $imgSwitch = $con.find("".openImg""); $searchCon.hide(); $imgSwitch.live(""click"", function () {{ $searchCon.slideToggle(""fast"", function () {{ if ($(this).css(""display"") == ""none"") {{ $imgSwitch.find(""img"").attr({{ ""src"": ""{20}"",""alt"":""展开搜索"" }}); }} else {{ $imgSwitch.find(""img"").attr({{ ""src"": ""{21}"",""alt"":""隐藏搜索"" }}); }} }}); }}); /*动态增删行*/ $.DynamicCon({{ container: "".{0}"", items: "".items"", maxCount: {26} }}); /*通用搜索中字段下拉框*/ $fieldSel =$con.find(""select[name='{3}']""); /*要搜索的字段下拉框*/ $fieldSel.live(""change"", function () {{ {0}.FieldChange(this); }}); /*回车提交查询*/ $con.find(""[name='{7}']"").live(""keypress"",function(event){{ if(event.keyCode==""13"") {{ $con.find("".btnSearch"").click(); return false; }} }}); $btnSearchObj=$con.find("".btnSearch""); $btnSearchObj.hover(function(){{$(this).find(""img"").attr({{""src"":""{24}""}});}},function(){{$(this).find(""img"").attr({{""src"":""{19}""}});}}); /*搜索:绑定提交事件*/ $btnSearchObj.live(""click"",function(){{ /*1:拼接所有搜索框中的条件为URL*/ var param=[]; var leftBracket,selectValue,selectDataType,symbol,inputValue,rightBracket,logic;/*左括号、字段、字段数据类型、运算符、输入区、右括号、逻辑符*/ $con.find(""tr.items"").each(function(){{ $selectField=$(this).find(""select[name='{3}']"");/*当前的下拉字段*/ inputValue=escape($.trim($(this).find(""[name='{7}']"").val()));/*输入区*/ selectDataType=$selectField.find(""option:selected"").attr(""type"");/*字段数据类型*/ selectValue=$selectField.val();/*当前下拉字段的值(字段)*/ if(selectValue==""""||selectValue==""-1""||inputValue=="""") {{ return true; }} leftBracket=$(this).find(""[name='{1}']"").val();/*左括号*/ symbol=$(this).find(""[name='{5}']"").val();/*运算符*/ rightBracket=$(this).find(""[name='{8}']"").val();/*右括号*/ logic=$(this).find(""[name='{10}']"").val();/*逻辑符*/ param.push(leftBracket+""|""+selectValue+""|""+selectDataType+""|""+symbol+""|""+escape(inputValue.replace(/[|]/,'').replace(/[,]/g,''))+""|""+rightBracket+""|""+logic); }}); /*2:将生成值放入隐藏域以便Get表单*/ $con.find("":hidden[name='{14}']"").val(param.toString()); $con.find(""input,select"").not(""[IsSubmit='1']"").attr({{""disabled"":""disabled""}});/*排除无关信息随表单提交*/ $con.closest(""form"").submit(); }}); /*页面加载时对搜索框的初始化*/ var currentUrl= {{""{14}"":""{15}""}};/*json*/ if(currentUrl[""{14}""]!=undefined&¤tUrl[""{14}""]!="""") {{ $con.find("".openImg"").click(); var strWhere=unescape(currentUrl[""{14}""]); var wp=strWhere.split(','); if(wp.length>1)/*刚开始本来有一行*/ {{ for(var m=0;m<wp.length-1;m++) {{ $con.find("".addBtn:eq(0)"").click(); }} }} /*给搜索框赋默认值*/ $trs=$con.find(""tr.items""); if(wp.length==$trs.length) {{ var values=[]; $trs.each(function(i){{ $leftBracketObj=$(this).find(""[name='{1}']"");/*左括号*/ $fieldObj=$(this).find(""[name='{3}']"");/*字段*/ /*where中有个字段类型(在字段对象的option中的type属性中)*/ $symbolObj=$(this).find(""[name='{5}']"");/*运算符*/ $inputValueObj=$(this).find(""[name='{7}']"");/*输入区(旧)*/ $rightBracketObj=$(this).find(""[name='{8}']"");/*右括号*/ $logicObj=$(this).find(""[name='{10}']"");/*逻辑符*/ values=wp[i].split('|');/*具体值*/ if(values.length==7)/*上面共有6个设置区(左括号、字段...)*/ {{ CommonSearch_CommonJs.SelectedObj($leftBracketObj[0],values[0]); CommonSearch_CommonJs.SelectedObj($fieldObj[0],values[1]); {0}.FieldChange($fieldObj[0]);/*调用字段下拉事件*/ {16} /*values[2]为字段类型*/ CommonSearch_CommonJs.SelectedObj($symbolObj[0],values[3]); $inputValueObj=$(this).find(""[name='{7}']"");/*输入区(新)上面调用了FieldChange事件后,此对象又重新生成了。*/ switch($fieldObj.find(""option:selected"").attr(""inputType"")) {{ case ""text"": $inputValueObj.val(unescape(unescape(values[4]))); break; case ""select"": CommonSearch_CommonJs.SelectedObj($inputValueObj[0],unescape(unescape(values[4]))); break; }} CommonSearch_CommonJs.SelectedObj($rightBracketObj[0],values[5]); CommonSearch_CommonJs.SelectedObj($logicObj[0],values[6]); }} }}); }} }}; }} }} </script>", /*0*/this.GetGuid, /*1*/this.LeftBracketName, /*2*/Common.GetEnumType(typeof(CommonState.LeftBracket)), /*3*/this.SelSearchTypeName, /*4*/this.selOptions, /*5*/this.SymbolName, /*6*/Common.GetEnumType(typeof(CommonState.Symbol)), /*7*/this.TxtSearchValueName, /*8*/this.RightBracketName, /*9*/Common.GetEnumType(typeof(CommonState.RightBracket)), /*10*/this.LogicName, /*11*/Common.GetEnumType(typeof(CommonState.logic)), /*12*/string.Format("{0}.GetInputOption(this);", this.GetGuid), /*13*/(int)CommonState.Symbol.包含, /*14*/this.StrParamName, /*15*/this.StrParamValue, /*16*/string.Format("{0}.GetInputOption($fieldObj[0]);", this.GetGuid), /*17*/this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "CommonSearch.Style.Images.add_search.gif"), /*18*/this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "CommonSearch.Style.Images.del_search.gif"), /*19*/this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "CommonSearch.Style.Images.search.gif"), /*20*/this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "CommonSearch.Style.Images.up.gif"), /*21*/this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "CommonSearch.Style.Images.down.gif"), /*22*/this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "CommonSearch.Style.Js.CommonJs.js"), /*23*/string.IsNullOrEmpty(this.strMsg)?"":string.Format(@"<br/><span style=""color:#f00;font-size:12px;"">{0}</span>",this.strMsg), /*24*/this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "CommonSearch.Style.Images.search2.gif"), /*25*/this.selInputOptionsEventJs, /*26*/this.MaxLine ); output.Write(Regex.Replace(str.ToString(), @"\s+", " ")); //output.Write(str.ToString()); } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace CommonSearch{ /// <summary> /// 字段类 /// </summary> public class SearchFieldInfo { /// <summary> /// 搜索控件字段的构造函数 /// </summary> /// <param name="Text">字段显示的名字</param> /// <param name="Value">字段对应的值的格式字符串,如:“A|B|C”【A:数据库中对应的真实字段名、B:此字段的类型,值为"dateTime、number、ntext、string"(ntext主要是为了去掉Like)】、C:输入区控件的类型:select为下拉框,text为文本框</param> /// <param name="FieldChangedHtml">字段发生change事件时,输入区的option(用于输入区为select的情况)</param> public SearchFieldInfo(string Text, string Value, string FieldChangedHtml) { this.Text = Text; this.Value = Value; this.FieldChangedHtml = FieldChangedHtml; } /// <summary> /// 字段显示的名字 /// </summary> public string Text { get; set; } /// <summary> /// 字段对应的值的格式字符串,如:“A|B|C” /// A:数据库中对应的真实字段名 /// B:此字段的类型,值为"dateTime、number、ntext、string"(ntext主要是为了去掉Like) /// C:输入区控件的类型:select为下拉框,text为文本框 /// </summary> public string Value { get; set; } /// <summary> /// 字段发生change事件时,输入区的option(用于输入区为select的情况) /// </summary> public string FieldChangedHtml { get; set; } }}
前台页面代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="Web.Index" %> <%@ Register Assembly="CommonSearch" Namespace="CommonSearch" TagPrefix="XCL" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title> <script src="Js/CommonSearch/jquery-1.5.2.min.js" type="text/javascript"></script> <script src="Js/CommonSearch/dynamicCon.js" type="text/javascript"></script> <script src="Js/DatePicker/WdatePicker.js" type="text/javascript"></script></head><body> <form id="form1" method="post"> <XCL:Search runat="server" ID="search1" FormType="post"/> <br /> <br /> <asp:Label ID="lbSql" runat="server" ForeColor="Red"></asp:Label> </form></body></html>
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using CommonSearch;namespace Web{ /// <summary> /// CommonSearch Demo /// </summary> public partial class Index : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { this.InitSearch(); } protected void InitSearch() { List<SearchFieldInfo> lstItem = new List<SearchFieldInfo>() { new SearchFieldInfo("系统ID","id|number|text",""), new SearchFieldInfo("告警类型","gaoJinType|string|text",""), new SearchFieldInfo("地区","area|string|select","<option value='杭州'>杭州</option><option value='武汉'>武汉</option>"), new SearchFieldInfo("基站号","基站号|string|text",""), new SearchFieldInfo("基站名","基站名|string|text",""), new SearchFieldInfo("告警开始时间","ACStartTime|dateTime|text",""), new SearchFieldInfo("告警结束时间","ACEndTime|dateTime|text",""), new SearchFieldInfo("停电时长(小时)","停电小时数|number|text","") }; this.search1.TypeList = lstItem; if (!string.IsNullOrEmpty(this.search1.StrSQL)) { this.lbSql.Text = this.search1.StrSQL; } } }}
- XCLNetSearch1.0(ASP.NET通用查询服务器控件)
- XCLNetSearch2.0(ASP.NET通用查询控件)发布啦
- asp.net通用列表查询控件
- asp.net服务器控件
- ASP.NET - 服务器控件
- ASP.NET服务器控件
- ASP.NET服务器控件
- Asp.net 服务器控件
- ASP.NET服务器控件
- ASP.NET服务器控件
- 打造通用ASP.NET数据分页控件
- 打造通用ASP.NET数据分页控件
- 打造通用ASP.NET数据分页控件
- 打造通用ASP.NET数据分页控件
- 打造通用ASP.NET数据分页控件
- 打造通用ASP.NET数据分页控件
- 打造通用ASP.NET数据分页控件
- 打造通用ASP.NET数据分页控件
- Android定制属于你自己的导航栏
- 设计包含min函数的栈
- 大型网站架构演变和知识体系
- 数理逻辑:谓词演算(目录)
- poj (3468)线段树lazy操作
- XCLNetSearch1.0(ASP.NET通用查询服务器控件)
- 和菜鸟一起学linux总线驱动之初识USB
- 编程之美2.5寻找最大的K个数
- JTextArea的多行整体左缩进与右缩进
- 数理逻辑:谓词演算(1)谓词演算公式
- 如何通过命令查看CentOS版本号
- 全排列
- 1029. Rabbit
- 递增单链表删除所有大于mink且小于maxK的元素。