Ajax与.NET 2.0高级程序设计 克隆Google Suggest的学习

 

最近学习Ajax 看了 《Ajax.NET 2.0高级程序设计》觉得Ajax对于提高用户体验还真不错,不过假如客户端禁用了JS,那我们只能说用户就少体验我们的设计

那样而言,Ajax只为了提高用户体验吗?对于一些正常操作我们要不要用。。。。。

诶。自己太菜了,很多东西都不明白。还是进入正题吧,现在我们就开始Ajax个得意的路程咯。呵呵

 看看效果先

1.首先定义好用到的样式先:

 <style type="text/css">
 .mouseOut{ 
       background: #C1D9F3; 

color: #000;

 }
 .mouseOver{

 background: #fff; color: #0000000;cursor: pointer;
 width:150px;
  }
 .Searcg{ position:relative; } /*相对定位*/
</style>

2.然后到用到的JS

<script type="text/javascript">

var ClientID;

//显示结果DIV

function ShowDiv(divid)

{

   if (document.layers) document.layers[divid].visibility="show";

   else document.getElementById(divid).style.visibility="visible";

}

//隐藏结果DIV

function HideDiv(divid)

{

   if (document.layers) document.layers[divid].visibility="hide";

   else document.getElementById(divid).style.visibility="hidden";

}

function BodyLoad()

{

    //加载的时候隐藏结果的DIV

    HideDiv(ClientID + "searchresults");

    

    // 焦点设置到输入框

var findtextbox = document.getElementById(ClientID + "keyword");

findtextbox.focus();

}

function ClearResults()

{   

// 删除表格中已有在行,清空DIV中的数据

var resultsdiv = document.getElementById(ClientID + "searchresults");

var counter = resultsdiv.childNodes.length;

for (var i = counter -1; i >= 0; i--)

{

resultsdiv.removeChild(resultsdiv.childNodes[i]);

}

}

//主要....

function LoadResults(searchterm)  

{

if (searchterm.length == 0)

{

// 如果输入框为空,将从结果表中复制所有的行

ClearResults();

HideDiv(ClientID + "searchresults");

return;

}

// 从服务器取得结果,这是我们实际的Ajax的调用

Anthem_InvokeControlMethod(

        "<%= ClientID %>",

        'RetrieveRows',

        [searchterm],

        LoadResultsCallback);

        // RetrieveRows 为在C#里的方法;   [searchterm] RetrieveRows 中的参数  ; LoadResultsCallback 为当执行完RetrieveRows方法后要执行的JS方法同时接受其查找数据的返回值..本例子为DataTable

}

//主要..

function LoadResultsCallback(result)

{

// XmlHttpRequest将返回到这个函数

ShowDiv(ClientID + "searchresults");

ClearResults();

//来自AJAX调用的回调结果,我们将返回的DataTable 赋值给items变量

var items = result.value;

var count = items.Rows.length;

// 我们在DOM中创建表格

var divResults = document.getElementById(ClientID + "searchresults");

var tblTable = document.createElement("table");

var tablebody = document.createElement("tbody");

var tablerow, tablecell, tablenode;

// DataTable的每一行上循环取出items 里面我们查询到的结果

for (var i = 0; i < count; i++)

{

var currenttext = items.Rows[i].AdminName; //这是我们查询返回的字段名,不能错“AdminName”

// 创建表格行并且添加到表格中

tablerow = document.createElement("tr");

tablecell = document.createElement("td");

// 设置表格属性也就是我们刚刚前面设置的样式,鼠标经过样式

tablecell.onmouseover = function(){this.className='mouseOver';};

tablecell.onmouseout = function(){this.className='mouseOut';};

tablecell.setAttribute("border""0");

tablecell.onclick = function(){ReplaceInput(this);}; //为表格添加单击事件,当用户单击的时候就把结果放到文本框中...

tablenode = document.createTextNode(currenttext);

tablecell.appendChild(tablenode);

tablerow.appendChild(tablecell);

tablebody.appendChild(tablerow);

}

tblTable.appendChild(tablebody);

divResults.appendChild(tblTable);

}

function ReplaceInput(tablecell)

{

   //具体对刚刚为单元格的单击事件,操作,就是替换输入框的值和选择的值

var inputbox = document.getElementById(ClientID + "keyword");

inputbox.value = tablecell.firstChild.nodeValue;

ClearResults();

HideDiv(ClientID + "searchresults");

}

</script>

3.自己定义控件的代码.  ucSuggestControl.ascx 

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ucSuggestControl.ascx.cs" Inherits="ucSuggestControl" %>

 <div class="Searcg">

        <input name="enployUnitName" id="enployUnitName"  runat="server" Width="100px"  onkeyup="LoadResults(this.value)"/>

 

        <div align="left" class="box" id="searchresults"   runat="server" style=" position:absolute;top:25px;left:0px; z-index:25;WIDTH:150px;BACKGROUND-COLOR:#C1D9F3 ;"> 

            </div>   <!-- position:absolute;主要是相对于 “Searcg”的绝对定位,不然显示结果多了会影响到div下的内容..-->

 </div>

4.ucSuggestControl后台的CS代码:

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

public partial class ucSuggestControl : System.Web.UI.UserControl

{

    protected void Page_Load(object sender, EventArgs e)

    {

        Anthem.Manager.Register(this); //注册

    }

    [Anthem.Method]

    public DataTable RetrieveRows(string searchterm)

    {

        SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Sell;Integrated Security=SSPI");

        DataTable dtReturn = new DataTable();

        conn.Open();

        SqlCommand cmd = new SqlCommand("Select Top 10 AdminName from TBL_AdminInfo where AdminName like @searchterm Order By AdminName", conn);

        SqlParameter param = new SqlParameter();

        param.ParameterName = "@searchterm";

        searchterm.Trim().Replace("'""''");

        searchterm += "%";

        param.Value = searchterm;

        cmd.Parameters.Add(param);

        SqlDataAdapter adpt = new SqlDataAdapter(cmd);

        adpt.Fill(dtReturn);

        conn.Close();

        return dtReturn;

}

    //因为用户控件受到ClientID 前缀引入的影响,我们必修考虑何时调用服务端函数的问题 Anthem库将抗逆性内嵌的ClientID 为一个重载的参数,允许恰当的导航机制的传输

    protected override void OnInit(EventArgs e)

    {

        

        base.OnInit(e);

        string jcode = "<script language=\"javascript\" type=\"text/javascript\">ClientID = '" + this.ClientID + "_" + "';BodyLoad();</script>";

        Page.ClientScript.RegisterStartupScript(typeof(Page),"suggest_control", jcode);

    }

}

5.最后是引用页面了

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="TestingForm.aspx.cs" Inherits="_Default" %>

<%@ Register Src="ucSuggestControl.ascx" TagName="ucSuggestControl" TagPrefix="uc1" %>

<!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>cs</title>

</head>

<body>

    <form id="form1" runat="server">

     <table border="1">

         <tbody>

        <tr>

        <td valign="top">

            <strong>h一个简单的例子</strong>

        </td>

        <td valign="top">

                        <uc1:ucSuggestControl id="UcSuggestControl1" runat="server">

                        </uc1:ucSuggestControl></td>

                </tr>

        </tbody>

</table>

    </form>

</body>

</html>

 

最后的话还有可以拓展一下,就是把查询到的结果放到一个地方,就不用每次当文本框值改变就去读出数据库...这正在想,有哪位朋友希望能指点一下偶这菜鸟..

.

....例子下载...

posted @ 2009-06-09 14:36  阿K&amp;LiveCai  阅读(469)  评论(0编辑  收藏  举报