日期:2010-06-10  浏览次数:20371 次

  前两天在网上下了个ajax组件体验了一下,感觉很不错。但后来开始想怎样能让它跟server控件交互呢,例如我上输出一个列表,就只有用js一条一条html的输出吗?不!!现在我说说怎样与 datagrid交互。

  注:ajax.net的组件可以到此网下载,我用的是for .net 1.1版本的。http://ajax.schwarz-interactive.de/

  1. 在引用中添加引用Ajax.dll。(这个很废话)

  2.在web.config中建立HttpHandler(这个当然是在system.web串里的)


<httpHandlers>
    <add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />
</httpHandlers> 

  3.在Global的Application_Start里加上个设置

        protected void Application_Start(Object sender, EventArgs e)
       {
            Ajax.Utility.HandlerPath = "ajax";
        }

  4.新建一个类DemoMethods,这个类里面提供了更新数据库和输出列表的方法。其实主要思想就是获得控件运行后生成的html,然后输出。 

 1        [Ajax.AjaxMethod]
 2        public int AddAjaxTable(string name)
 3        {
 4            //输入一个字符串,然后更新
 5            SqlConnection conn = new SqlConnection( System.Configuration.ConfigurationSettings.AppSettings["connectionString"] );
 6            SqlCommand cmd = new SqlCommand("insert into ajaxTable(name) values('"+name+"')", conn);
 7            cmd.Connection.Open();
 8            int result = cmd.ExecuteNonQuery();
 9            conn.Dispose();
10            cmd.Dispose();
11            return result;
12        }
13
14        [Ajax.AjaxMethod]
15        public string GetAjaxTable()
16        {
17            //这个方法就是拿到datagrid生成出来的html
18            SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["connectionString"]);
19            SqlCommand cmd = new SqlCommand("select * from ajaxTable order by id", conn);
20            SqlDataAdapter ap = new SqlDataAdapter( cmd );
21            DataSet ds = new DataSet();
22            ap.SelectCommand.Connection.Open();
23            ap.Fill( ds, "db" );
24
25            conn.Dispose();
26            cmd.Dispose();
27
28            //实例化一个datagird类并设置好数据源
29            DataGrid dg = new DataGrid();
30            dg.DataSource = ds.Tables["db"];
31            dg.DataBind();
32
33            //实例化一个HtmlTextWriter的类
34            System.Text.