天天看點

請求aspx頁面的WebMethod

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" rel="external nofollow"  target="_blank" οnclick="return g();">Go to baidu..</a>
         <br />
         <a href="http://www.sina.com.cn" target="_blank" rel="external nofollow"  target="_blank" οnclick="f();">Go to sina..</a>
         <br />
         <input type="button" οnclick="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。

繼續閱讀