用PageMethods进行Server和Client通信

来源:互联网 发布:蚂蜂窝 知乎 编辑:程序博客网 时间:2024/05/12 23:23

WebService and PageMethods的应用

 

想要使用ASP.NET AJAX在客户端JavaScript中异步调用服务器端Web Service,我们需要:

1 为Web Service类或需要暴露给客户端的Web Service方法添加[ScriptService]
      属性;

2 为Web Service中需要暴露给客户端的方法添加[WebMethod]属性;

3 在页面中的ScriptManager控件中添加对该Web Service的引用;

4 在客户端使用如下JavaScript语法调用该Web Service:
      [NameSpace].[ClassName].[MethodName](param1, param2,..., callbackFunction)

5 为客户端异步调用指定回调函数,在回调函数中接收返回值并进一步处理。

-----------------------

想要使用ASP.NET AJAX在客户端JavaScript中异步调用定义在ASP.NET页面中的方法,我们需要:

1 将该方法声明为公有(public);

2 将该方法声明为类方法(C#中的static,VB.NET中的Shared),而不是实例方法;

3 为该方法添加[WebMethod]属性;

4 将页面中ScriptManager控件的EnablePageMethods属性设置为true;

5 在客户端使用如下JavaScript语法调用该页面方法:
      PageMethods.[MethodName](param1, param2,..., callbackFunction);

6 为客户端异步调用指定回调函数,在回调函数中接收返回值并进一步处理。

 

PageMethods Simple:

 

Server

 

[WebMethod]
    public static void AddRootCauseGroup(string groupId,string description)
    {
        try
        {
            string alertMsg="操作不合法:"+groupId+"已存在!";
            bool RecrodExist = CheckRecordExist.checkRecordExist("groupid", "rootcause_group", "groupid",groupId);
            if (!RecrodExist)
            {
                RootCauseGroup.insertRootCauseGroup(groupId, siteId, description, userIndex, userIndex);
            }
            else
            {
                MessageBox.Show(alertMsg);
            }
        }
        catch (Exception ee)
        {
            throw ee;
        }
    }

Client

 

  function ButtonOk_onclick()
    {
        var groupId=window.document .getElementById("TextBoxRootGroupId").value;
        var description=window.document .getElementById("TextBoxDescription").value;
        PageMethods.AddRootCauseGroup(groupId,description);
        returnValue1();
    }

原创粉丝点击