1.在项目中添加此dll的应用,同时需要在 webconfig的 <system.web> 里面 加上
<httpHandlers>
<add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory,Ajax"></add>
</httpHandlers>
2.在应用页面的Page_Load中添加
Ajax.Utility.RegisterTypeForAjax(typeof(页面名));
3.在要调用的后台方法前加ajax的声明
①操作session时
[Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.Read)]
public void GetBranchSelectIndex(int selectIndex)
{
Session["BranchSelIndex"] =selectIndex;
}
②其他操作的时候
[Ajax.AjaxMethod()]
public DataTable DependLineGetBranch(string strLineCD)
{
clsMainDB mdbBranch = new clsMainDB();
dtBranchInfo = mdbBranch.GetBreadBranchInfo(strLineCD);
int i=dtBranchInfo.Rows.Count;
return dtBranchInfo;
}
4.在前台的js中写function中调用此方法
var abc=页面名.方法名(参数).value;//有返回值
页面名.方法名(参数);//没有返回值
③注意点
(1).不可以读取 cookie的值,但是可读session的值 不能使用Request去参数值,不能使用控件名字
(2)方法中不能出现后台的控件,比如 this.xxxx 会提示[未定义]
(3)不能调用重载方法,如果重载方法将调用失败。
前台代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AjaxExample.aspx.cs" Inherits="AjaxExample" %>
<!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>
function AClick()
{
alert('The AjaxMethod start ');
var msg= AjaxExample.WriteText().value;
alert(msg);
alert('The AjaxMethod end ');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<a href="javascript: AClick();">请点击这里</a>
<asp:Literal ID="ltrTree" runat="server"></asp:Literal>
</div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>
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;
public partial class AjaxExample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Ajax.Utility.RegisterTypeForAjax(typeof(AjaxExample),Page);
}
[Ajax.AjaxMethod()]
public string WriteText()
{
//ChangeLabel();
//Response.Write("ok");
//return Request["str"];
//Page.RegisterStartupScript("", "<script>alert('2');</script>");
return "后台方法成功调用!";
}
public void ChangeLabel()
{
Label1.Text = "abcdef";
}
}