仿百度搜索、重定向

 功能图如下:   
            
功能说明:仿照百度搜索的自动完成搜索功能,完整版。     
            /**************技术:.NET******************/
                              /*******第一次编辑时间:2012年07月16日*********/
                              /*********修改时间:2012年08月88日**********/
                              /**********修改说明:本实例存在缺陷**********/
                              /*************Author:jsping**************/
           /*************QQ:759963787************/

今天有空,在原来我写的文章的基础上对自动搜索文本框的功能加以完善,使页面可以在不刷新的情况下实现搜索、页面重定向。

程序主要代码:

Test.aspx代码:

<tr>
        <td class="formCellOdd">
            委托物业地址
        </td>
        <td class="formCellBig" colspan="3">
            <div id="search">
                <asp:DropDownList ID="dropqy" runat="server" key="区域" DataValueField="DistrictID"
                    DataTextField="name" onchange="RegionChange()">
                </asp:DropDownList>
                <asp:DropDownList ID="ddlCommunity" runat="server" key="街道小区" DataTextField="CommunityName"
                    DataValueField="CommunityID">
                </asp:DropDownList>
                <asp:TextBox ID="txtdz" runat="server" key="地址">
                </asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="*"
                    ControlToValidate="txtdz" ValidationGroup="val" Display="Dynamic">
                </asp:RequiredFieldValidator>
            </div>
        </td>
    </tr>

脚本代码:

说明:主要实现两个DropDownList的联动

function RegionChange() {
        var RegionName = "<%=dropqy.ClientID %>";   //区域
        var CommunityName = "<%=ddlCommunity.ClientID %>";  //街道
        $('#' + CommunityName + ' option').remove();
        $.ajax({
            type: "POST",
            url: "处理页面的URL",
            data: { "ParentName": $('#' + RegionName).val() },
            success: function (msg) {
                if (msg != "") {
                    var regions = msg.split(",");
                    $('#' + CommunityName).append("<option value='0'>--请选择街道--</option>");
                    $('#' + CommunityName + ' option:first').attr('selected', 'true');
                    for (var i = 0; i < regions.length - 1; i++) {
                        if (i % 2 == 0) {
                            $('#' + CommunityName).append("<option value=" + regions[i] + ">" + regions[i + 1] + "</option>");
                            $('#' + CommunityName).val(regions[i + 1]);
                        }
                    }
                }
                else {
                    $('#' + CommunityName).append("<option value='0'>--请选择街道--</option>");
                }
            }
        });
    }

脚本代码:

说明:在文本框中输入数据后,根据此代码到处理页面进行模糊查询,然后select某一项后,通过此代码到处理页面进行数据的处理(比如字符串拼接等,关键就是设置查询

   数据的返回格式),然后把数据以某种形式返回来,并且通过此代码获取返回的数据,然后进行分割,最后绑定到具体的控件上就OK了。

 

$(function () {
        var d = "<%=txtdz.ClientID %>";
        var RegionName = "<%=dropqy.ClientID %>";
        var CommunityName = "<%=ddlCommunity.ClientID %>";
        $("#" + d).autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: 处理页面的Url?keyword=" + encodeURIComponent(request.term),
                    data: {
                        name: request.term
                    },
                    dataType: "json",
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { value: item };
                        }));
                    }
                });
            },
            select: function (event, ui) {

      //数据ui.item.value是所选择的项
                //$('#' + RegionName + ' option').remove();
                $.ajax({
                    type: "POST",
                    url: "处理页面的URL",
                    data: { "keyword": encodeURIComponent(ui.item.value) },
                    success: function (data) {
                        if (data != "") {
                            var returnValue = data.split(",");   //获取的数据
                            var ZLNX = "<%=txtzlnx.ClientID %>";   //租赁年限
                            var QY = "<%=dropqy.ClientID %>";  //区域
                            var JD = "<%=ddlCommunity.ClientID %>";  //街道
                            var DZ = "<%=txtdz.ClientID %>";  //地址
                            $('#' + ZLNX).val(returnValue[0]);

          。。。。。。。。。//数据有省略。。。。。。。。
                            //区域
                            $('#' + QY + ' option').remove();
                            $('#' + QY + ' option:last').attr('selected', 'true');
                            $('#' + QY).append("<option value=" + returnValue[20] + ">" + returnValue[21] + "</option>");
                            $('#' + QY).val(returnValue[21]);
                            //街道
                            $('#' + JD + ' option').remove();
                            $('#' + JD + ' option:last').attr('selected', 'true');
                            $('#' + JD).append("<option value=" + returnValue[22] + ">" + returnValue[23] + "</option>");
                            $('#' + JD).val(returnValue[23]);

 

                            $('#' + DZ).val(returnValue[24]);                        

 

                        }
                        else {
                            alert("没有对应的数据.");
                        }
                    }
                });
            }
        });
    });

Test.aspx.cs代码:

     protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //此处可以加上页面需要绑定的控件的数据源等代码,由于我这个页面是用户控件,可以多次使用。

      //在另一个页面加载的是历史数据,所以还需要写额外的一些代码。。。。

                  ddlCommunity.Items.Insert(0,DataSource.Rows[0]["街道小区"].ToString());
                  dropqy.Items.Insert(0,DataSource.Rows[0]["所属区域"].ToString());
            }

        }

下面是一般处理页面:

说明:用于下拉列表的联动。

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string RegionID = context.Request.Form["ParentName"];   //获取区域名称

            if (RegionID == "。。。。。")
            {
                return;
            }
            if (!string.IsNullOrEmpty(RegionID))
            {
                string TheReturnValue = null;   //返回值

      //省略数据库查询代码。。。
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                            TheReturnValue += ds.Tables[0].Rows[i][0].ToString() + "," + ds.Tables[0].Rows[i][1].ToString();
                            TheReturnValue += ",";
                }
                 context.Response.Write(TheReturnValue);
              }
             else
             {
                 context.Response.Write("false");
             }
        }

当在文本库输入数据时把类似的数据显示在文本框下面供选择:

        SqlConnection conn = null;
        SqlCommand cmd = null;
        SqlDataReader reader = null;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string keyword = context.Request.QueryString["keyword"];
            keyword = System.Web.HttpUtility.UrlDecode(keyword);

            if (keyword != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer(); // 通过JavaScriptSerializer对象的Serialize序列化为["value1","value2",...]的字符串
                string jsonString = serializer.Serialize(GetFilteredList(keyword));
                context.Response.Write(jsonString); // 返回客户端json格式数据
            }
            else
            {
                context.Response.Write("[]");
            }
        }

         /// <summary>
        /// 根据关键字过滤数据
        /// </summary>
        /// <param name="keyword">关键字</param>
        /// <returns>过滤数据</returns>
        private string[] GetFilteredList(string keyword)
        {

    //此处省去一万行
           cmd = new SqlCommand("sp_HCS_GetHistoryInfoOfHouseByKey", conn);
           cmd.CommandType = CommandType.StoredProcedure;
           cmd.Parameters.Add("key", SqlDbType.NVarChar, 50);
           cmd.Parameters["key"].Value = "%" + keyword + "%";

           reader = cmd.ExecuteReader();
           List<string> nameList = new List<string>();
           try
           {
               while (reader.Read())
               {
                    string name = reader["PAddress"].ToString();
                    nameList.Add(name);
                 }
            }
           catch (SqlException ex)
           {
                 throw ex;
           }
           return nameList.ToArray();
        }

 最后,当选中某一行数据时,页面进行无刷新的执行某种操作:比如页面重定向时把点击的数据作为参数,或加载本页面的历史数据

       public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string address = context.Request.Form["keyword"];
            address = System.Web.HttpUtility.UrlDecode(address);
            if (address != null)
            {
                context.Response.Write(ExecuteLoad(address));
            }
           
        }
        public static string ExecuteLoad(string key)
        {
            string TheReturnValue = null;   //返回值
            DataSet ds = DatabaseHelper.InvokeCommandWithTransaction("sp_History", key); 

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                {
                    TheReturnValue += ds.Tables[0].Rows[0][j].ToString() + ",";
                }
            }
            //客户信息
            for (int i = 0; i < ds.Tables[1].Rows.Count; i++)
            {
                for (int j = 0; j < ds.Tables[1].Columns.Count;j++ )
                {
                    TheReturnValue += ds.Tables[1].Rows[0][j].ToString() + ",";
                }
            }

            return TheReturnValue;

        }

OK,现在就可以实现了之前我用的方法比较不友好,现在更新完毕,总算了了一件心事。

posted @ 2012-07-26 12:44  jsping68  阅读(1083)  评论(0编辑  收藏  举报