C# 如何使用ajax

来源:互联网 发布:mysql error 1227 编辑:程序博客网 时间:2024/05/20 13:09

 

1.首先下载ajax.dll,一个百度一下都有下载的!自行查找。

2.把ajax.dll导入到工程。右键工程-->添加引用--->浏览,找到下载好的ajax.dll文件,点击确定,这时候在工程目录下多了一个bin文件夹,里面就有ajax.dll文件,这证明引入ajax.dll成功了。

3.设置配置文件web.config。

在Web.config文件下的 <system.web>节点里面添加以下代码即可:

   

    <httpHandlers>      <add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro"/>    </httpHandlers>
4.使用演示:4.1首先要对ajax进行注册。 在aspx.cs代码中的Page_Load方法里面对ajax进行注册,注册方式为Ajax.Utility.RegisterTypeForAjax(typeof(命名空间.类名)),假如没有命名空间可以直接写类名。代码如下:
public partial class ObjManage : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        Ajax.Utility.RegisterTypeForAjax(typeof(ObjManage));    }}
4.2编写cs的方法,供javascript调用。cs方法前端必须要有[Ajax.AjaxMethod],然后方法必须是公有public、静态static。例如:
       [Ajax.AjaxMethod]    public static string getString(string str)    {        string strResult = "The string is " + str;        return strResult;    }
4.3javascript调用cs方法。调用的格式是:类名.方法名(参数),例如:
function alertString() {            var str = ObjManage.getString("myAjax").value;            alert(str);        }

这样就完成了。这个是通过测试的,假如有什么问题,可留言。下面给出完成的源码,对于Web.config的代码就不给了,自己安装第3步设置配置文件web.config进行设置就OK了。cs代码:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class ObjManage : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        Ajax.Utility.RegisterTypeForAjax(typeof(ObjManage));    }    [Ajax.AjaxMethod]    public static string getString(string str)    {        string strResult = "The string is " + str;        return strResult;    }}


--------------------------------------------------

aspx代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ObjManage.aspx.cs" Inherits="ObjManage" %><!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 type="text/javascript">        function alertString() {            var str = ObjManage.getString("myAjax").value;            alert(str);        }    </script></head><body>    <form id="form1" runat="server">    <div>        <input type="button" value="获取信息" onclick="alertString();" />    </div>    </form></body></html>