`

请求aspx页面的WebMethod

    博客分类:
  • Ajax
阅读更多

Asp.net可以在aspx页面中添加ScriptManager,这样就允许将WebMethod添加在aspx页面中,而以往通常都是新建asmx文件,利用webservice提供webmethod供请求。这里列出利用ajax请求aspx页面中的webmethod的方法,当然也可以利用ScriptManager创建的PageMethods的js对象直接访问后台代码中的webmethod。

linktest.aspx代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="linktest.aspx.cs" Inherits="linktest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" src="MyJs/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="MyJs/jquery.json-2.3.min.js"></script>
    <script type="text/javascript">
        function g() {
            var flag = false;
            $.ajax({
                type: "POST",
                async: false,
                url: "linktest.aspx/InsertComment",
                //data: $.toJSON({ "thecontent1": 'hello' }),
                data: window.JSON.stringify({ "thecontent1": 'hello' }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function() { alert('出错了'); },
                success: function(json) {
                    if (json.d) {
                        alert("successs");
                        flag = true;
                    }
                    else {
                        alert("kao");
                    }
                }
            });
            return flag;
        }

        function f() { 
            $.ajax({
                type: "POST",
                async: true,
                url: "linktest.aspx/GetJsonObject",
                data: $.toJSON({ "p": 'hello' }),
                //data: window.JSON.stringify({ "thecontent1": 'hello' }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function() { alert('出错了'); },
                success: function(json) {
                    alert("" + json.d.key1 + json.d.keyofarray[2] + json.d.keyofobject.subkey);  
                }
            }); 
        }

        function h() {
            //不通过ajax,直接通过scriptmanager访问后台的pagemethod
            PageMethods.TestMethod("dlut", OnSucceeded1, OnFailed); //后两个参数为请求成功和失败的回调函数
        }
        function OnSucceeded1(result, userContext, methodName) {
            if (methodName == "TestMethod") {
                alert(result);
            } 
        }
        function OnFailed(error, userContext, methodName) {
            if (error !== null) {
                alert("error..");
            }
        }
        
    </script>
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="sm1" EnablePageMethods="true" runat="server" /> 
    <div>
         <a href="http://www.baidu.com" target="_blank" onclick="return g();">Go to baidu..</a>
         <br />
         <a href="http://www.sina.com.cn" target="_blank" onclick="f();">Go to sina..</a>
         <br />
         <input type="button" onclick="h();" value="Request PageMethod" />
    </div>
    </form>
</body>
</html>

 这里写了3个测试,前两个是通过Jquery的ajax,最后一个直接通过PageMethods请求pagemethod。要知道,aspx后台要想在新标签页中打开一个链接可有点不容易,这里利用A标签onclick里Ajax请求,如果onclick返回false,则不会跳转。

还要注意的是$.ajax的data参数,因为设置成了json格式,所以利用$.toJSON将js对象转换成json对象,其实用window.JSON.stringify也行,但是这个不是所有浏览器都奏效。

前台往后台传参数这样将js对象转换成json就行,只要里面的属性和后台的webmethod的参数对应就行,如果后台的webmethod的参数是一个C#对象,同样的,只要js对象的属性和C#对象的属性对应就可以了。

还要注意的就是ajax的async标志,这个很好理解。前台得到返回结果以后取得返回值记住是在json.d下。

后台代码linktest.aspx.cs代码如下:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

public partial class linktest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["test"] = "hey";
        }
    }

    [System.Web.Services.WebMethod]
    public static bool InsertComment(string thecontent1)
    {
        return thecontent1.Equals("hello");
    }

    [System.Web.Services.WebMethod]
    public static string TestMethod(string p)
    {
        return p + " data from back..";
    }

    [System.Web.Services.WebMethod]
    public static SortedDictionary<string, object> GetJsonObject(string p)
    {
        SortedDictionary<string, object> results = new SortedDictionary<string, object>();
        results.Add("key1","value1");
        results.Add("key2", p); 
        results.Add("keyofarray",new int[]{1, 2, 3});

        SortedDictionary<string, object> subitem = new SortedDictionary<string, object>();
        subitem.Add("subkey","hah");

        results.Add("keyofobject", subitem);

        return results;
    }

    [System.Web.Services.WebMethod(EnableSession=true)]
    public static SortedDictionary<string, object> ObjectParameterTest(Books p)
    {
        SortedDictionary<string, object> results = new SortedDictionary<string, object>();
        results.Add("key1", p.bookTitle);
        results.Add("key2", HttpContext.Current.Session["test"].ToString() ); 
        return results;
    }
}

 最后一个ObjectParameterTest方法的参数是一个C#对象,前台传递的时候只要json的属性跟它对应就可以了。这里还展示了怎样取到session。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics