方法一:javascript
一、首先创建一个按钮,在后台将调用或处理的内容写入button_click中; html
二、在前台写一个js函数,内容为document.getElementById("btn1").click(); 前端
三、在前台或后台调用js函数,激发click事件,等于访问后台c#函数;方法二:java
一、函数声明为public c#
后台代码(把public改为protected也能够) ssh
public string methodname() //注意该方法不能为void,不然执行会报错 {//在这以前能够作任何一些服务端的操做,能够不把返回值做为目的,而是要执行一些服务端的代码。函数
return ""; } 二、在html里用<%=fucntion()%>能够调用前台脚本 spa
<script language=javascript>htm
var a = "<%=methodname()%>";alert(a); 事件
eval("<%=methodname()%>"); //若是只是要执行服务端的一些代码也能够写为以下,这样就能够执行服务端代码了
</script>1.在后台建立方法,必须是static(静态的),方法必须是public类型的,不然访问不到会报异常,
接着要在该方法头部上加上[System.Web.Services.WebMethod],来标注方法特性。2.在前台页面加入ScriptManager控件,并把其EnablePageMethods属性设为true。
3.调用PageMethods,因为该方法有不少重载,如今只说最简单的实现。PageMethods.FunctionName(回调的js方法); //其中FunctionName为后台建立的静态方法名,回调js方法为前台接受结果的方法。
PageMethods例子:
后台代码:
一.无参数方法
[System.Web.Services.WebMethod] public static string ShowValue() { return "js调用后台方法"; }二.有参数方法
[System.Web.Services.WebMethod] public static string ShowValue2(string msg) { return msg;}
前端代码:
<script type="text/javascript">
//调用后台无参数方法
function bclick() { PageMethods.ShowValue(sshow); } function sshow(val) //回传方法用val接受后台代码ShowValue的执行结果 { document.getElementById("show").innerText = val;}
//调用后台有参数方法
function bclick2() { var text = "test"; PageMethods.ShowValue2(text,sshow2); } function sshow2(val) //回传方法用val接受后台代码ShowValue的执行结果 { document.getElementById("show").innerText = val; } </script> < input id="Button1" type="button" value="click" onclick="bclick();" /> < input id="Button2" type="button" value="click2" onclick="bclick2();" /> < div id="show"></div>