asp.net javascript客户端调用服务器端方法

如何用js调用服务器端方法。首先服务器端方法的格式如下

        [System.Web.Services.WebMethod]
        public static void serverMethod(string url)
        {
            WebClient wc = new WebClient();
            StringBuilder postData = new StringBuilder();
            postData.Append("multigateway=" + m_username);
            //下面是GB2312编码
            byte[] sendData = Encoding.GetEncoding("GB2312").GetBytes(postData.ToString());
            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            wc.Headers.Add("ContentLength", sendData.Length.ToString());

            byte[] recData = wc.UploadData(url, "POST", sendData);
        }

标记为红色的很重要,是服务器方法的强制要求,这样才能被客户端直接调用

客户点js调用如下

    <script type="text/javascript">
        function CallServerMethod(para) {
            PageMethods.SetMultiGatwayMessage(para,onsuccess);
        }

        function onsuccess(callbackValue)  //调用完后台方法后回调函数,获取后台返回的参数
        {
        }
    </script>

最后前端网页中千万别忘记添加ScriptManager 并把enablePageMethods属性设为true
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"  EnablePageMethods="true"></asp:ScriptManager>
        </div>
    </form>
</body>

posted @ 2015-10-19 15:46  beautifulday  阅读(461)  评论(1编辑  收藏  举报