​C#WebForm里面aspx,ajax请求后台。。。​

  虽然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 οnclick='GetMsg()'>
测试WebMethod</button>
<button οnclick='GetMsg1()'>
测试</button>
<input id="test" type="button" value="contrller" οnclick="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>