ASP.NET中JavaScript 调用后台代码

前序:在不需要右击页面或回发的情况下刷新页面,即JS调用后台代码;

方法一:调用隐藏服务端按钮的点击事件

1、在前端放一个隐藏按钮,,将需要调用的后台代码写入OnClick事件中;

2、在前台写一个js函数,函数体为document.getElementById("<%=btnID.ClientID%>").click();

3、在需要刷新的地方调用js函数,即可调用按钮OnClick事件;

4、此方法适用无返回值;

方法二:JS中直接用<%=MethodName()%>调用

1、在后台写好方法,public或是protected;

2、在前台写一个js函数,函数体为var result = "<%=MethodName()%>" 或是 直接 eval("<%=MethodName()%>");

3、在需要刷新的地方调用js函数,即可调用后台方法;

4、此方法适用带返回值;

方法三:利用PageMethod调用

PageMethod方法介绍:PageMethods.FunctionName(Paramter1,Parameter2,…,SuccessMethod, FailedMethod, userContext);其中,前面Paramter1,Parameter2,…,表示的是FunctionName的参数,类型是Object或Array;SuccessMethod是需要使用后台返回结果的Js方法,FailedMethod是当后台的csFunctionName方法发生异常情况下的执行的Js方法(容错处理方法),userContext是可以传递给SuccessMethod方法,或是FailedMethod方法的任意内容。实现方法三按照以下步骤:

1.后台方法必须是public static 的,

方法头部上加上[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 "HelloWord= =C#";}

前端代码:

<script type="text/javascript">function bclick(){PageMethods.ShowValue(HelloWord);//调用有参数方法PageMethods.ShowValue(‘123’ , HelloWord);}function HelloWord(result) //回调方法接受后台代码的执行结果{alert(result);}//调用后台有参数方法function bclick2(){var text = "test";PageMethods.ShowValue2(text,sshow2);}</script>

方法四:JQuery Ajax 异步调用

百度一大堆

梦想从来不会选择人,它是上天赋予每个人构建未来蓝图的神奇画笔。

ASP.NET中JavaScript 调用后台代码

相关文章:

你感兴趣的文章:

标签云: