码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-10-19 17:02:28      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

如何用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>

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

标签:

原文地址:http://www.cnblogs.com/tianmochou/p/4892108.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!