雖然WebForm裏面有那些基本控件,後臺CS裏面也有許許多多的控件的方法。但是不見得有些標籤不需要進行後臺的訪問,下面介紹一下三種aspx中訪問後臺的方式。。
第一種:WebMethod (靜態方法):
//通過WebMethod的靜態方法,訪問自己cs後面的方法
[WebMethod] public static string GetMsgByWeb()
{
return "Hello Word";
}
第二種:映射請求方法:
/// <summary>
/// 通過映射訪問自己cs後面方法
/// </summary>
/// <param name="page"></param>
/// <param name="method"></param>
/// <returns></returns>
public static void GetJsonByPage(Page page,string method="act")
{
var m_method = page.Request[method];
if (m_method != null)
{
try
{
var res = page.GetType().GetMethod(m_method, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance).Invoke(page,null);
if (res != null)
page.Response.Write(res);
}
catch (Exception ex)
{
page.Response.Write(JsonConvert.SerializeObject(ex));
}
page.Response.End();//將當前所有緩衝輸出到客戶端,停止該頁的執行,否則頁面HTML也會輸出
}
}
第三種:MVC模式請求控制器:
public class TestController : System.Web.Mvc.Controller
{
public string GetText()
{
var str =Request["value"] + "";
return str;
}
}
前端代碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="testWebMethod.aspx.cs"
Inherits="StudyProgram.Pages.testWebMethod" %>
<!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 src="../Scripts/JQuery-1-10-2.js" type="text/javascript"></script>
<style>
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<button onclick='GetMsg()'>
測試WebMethod</button>
<button onclick='GetMsg1()'>
測試</button>
<input id="test" type="button" value="contrller" onclick="fnGetMsg(this)" />
</div>
</form>
<script>
$(function () {
//GetMsg();
});
//請求後臺靜態方法
function GetMsg() {
$.ajax({ //調用的靜態方法,所以下面必須參數按照下面來
url: 'testWebMethod.aspx/GetMsgByWeb',
type: 'post',
contentType: "application/json",
dataType: 'json',
data: "{}", //必須的,爲空的話也必須是json字符串
success: function (data) {//這邊返回的是個對象
console.log(data);
if (data != null)
alert(data.d);
}
});
}
//通過後臺映射方法請求數據
function GetMsg1() {
$.ajax({ //調用的靜態方法,所以下面必須參數按照下面來
url: '?method=GetMsgByWeb1',
type: 'post',
data: { id: 'huage' },
dataType: 'text',
success: function (data) {
console.log(data);
if (data != "")
alert(data);
}
});
}
//通過請求控制器得到結果
function fnGetMsg(btn) {
var value = $(btn).val();
// $.post("../Controllers/Controller/Test", function (res) {
// if (!res)
// alert(res);
// });
$.ajax({ //調用的靜態方法,所以下面必須參數按照下面來
url: "../../Test/GetText",
type: 'post',
data: { value: value },
dataType: 'text',
success: function (data) {//這邊返回的是個對象
console.log(data);
if (data)
alert(data);
}
});
}
</script>
</body>
</html>
原文地址: