通过ajax访问aspx的CodeBehind中的方法

时间:2023-03-10 02:40:22
通过ajax访问aspx的CodeBehind中的方法

引言

在项目中突然看到,aspx中的ajax可以访问aspx.cs中的方法,觉得很新奇,也许是lz少见多怪,不过,真的有发现新大陆似的那种兴奋,你也许知道这代表什么,学会了这种方式,代表你以后,可以建更少的页面,更少ashx,更少的.....能不兴奋吗?在lz的印象中,ajax一般都和一般处理程序联系起来的,请求另外的aspx页面就不说了,而请求自身CodeBehind中的方法真的很少见,这里记录一下,也许也有跟我一样不知道的朋友,希望能帮到你。只是知道ajax可以访问webservice中加webmethod特性的方法,没想到也可以访问aspx中加webmethod的方法。幸亏现在知道了。

ajax配置

测试:模拟一个小学二年级的加法运算,通过ajax将值传给default.aspx.cs中的Add方法,通过该方法完成计算,返回结果。

Default.aspx

ajax的使用方法这里就不多说了。

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Wolfy.AjaxSelf.Default" %>

 <!DOCTYPE html>

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript" src="jquery-1.10.2.js"></script>
<script type="text/javascript">
$(function () {
$("#btn").click(function () {
var num1 = $("#num1").val();
var num2 = $("#num2").val();
$.ajax({
type: "POST",//
url: "Default.aspx/Add",
data: "{num1:'"+num1+"',num2:'"+num2+"'}",
contentType: "application/json",
dataType: "json",
success: function (data) {
$("#num3").val(data.d);
},
error: function (msg) {
alert(msg.status);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="num1" name="name" value="" />
<label>+</label>
<input type="text" id="num2" name="name" value="" />
<input type="button" name="name" id="btn" value="=" />
<input type="text" id="num3" name="name" value="" /> </div>
</form>
</body>
</html>

Default.aspx.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Wolfy.AjaxSelf
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
[WebMethod]
public static int Add(int num1, int num2)
{ return num1 + num2; }
}
}

测试结果

通过ajax访问aspx的CodeBehind中的方法

注意

ajax中的type必须为“POST”,否则:
通过ajax访问aspx的CodeBehind中的方法

Ajax中的data,中键必须与方法中参数名字相同,否则:

通过ajax访问aspx的CodeBehind中的方法

codeBehind中的方法必须加WebMethod特性,必须为静态方法,否则:

通过ajax访问aspx的CodeBehind中的方法

这是其中需要注意的地方,至于为什么必须是静态的,lz也问了很多人,也不是很懂,这里就不班门弄斧了,有知道的朋友,留下你的足迹,也可以相互沟通一下。

总结

这种方式,也是在看项目中,遇到的,真的是第一次见,真的很开心,现在遇到了。遇到了,就拿出来,记录一下,分享一下,开心一下。

这种方式跟ajax访问webservice确实很像,但是为什么必须是静态的呢?也许你知道,请一起讨论,让更多的朋友也知道。