Asp.net AJAX调用后台静态方法总结

从客户端调用后台静态方法

1.Ajax Library方式

C#代码:

[WebMethod]
public static DateTime GetCurrentTime(string str)
{
    return DateTime.Now;
}

JS代码:

    <form id="form1" runat="server">
    <script language=javascript type="text/javascript">
        function GetCurrentTime1() {
            PageMethods.GetCurrentTime('NewEgg ajax training', CheckIsSuccess);
        }
        function CheckIsSuccess(result) {
            alert(result);
        }
     </script>
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        <input id="Button1" type="button" value="客户端控件调用服务器端的方法" onclick="GetCurrentTime1()" />
    </div>
    </form>

说明:

C#方法必须加 "[WebMethod]"

前台页面必须使用引用 服务器控件

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

调用方法: PageMethods.后台方法名(参数[,参数....], 成功后调用的方法名);

Ajax Library

image

image

2. jQuery方式

C#代码:

[WebMethod]
public static string ABC(string ABC)
{
    return ABC;
}

JS代码:

	$().ready(
            function() {
                $("#AjaxDemo").click(function() {
                    $.ajax({
                        type: "POST",
                        url: "Default.aspx/ABC",
                        data: "{'ABC':'test'}",
                        contentType: "application/json; charset=utf-8",
                        success: function(msg) {alert(msg); }
                    })
                })
            }
        )

说明: 必须引用jQuery库文件.

3. 还有一种好像是要引用AJAX.dll文件的. 在后台注册前台方法. 这个好像在.net2.0的时候用的比较多. 具体没仔细研究.

还望有其他更简单方法的同学互相交流下~

posted @ 2012-05-03 12:15  hen  阅读(12618)  评论(6编辑  收藏  举报