webform中頁面傳遞Json資料

jdmgm發表於2012-10-12

簡單的webform頁面中傳遞json資料,但是安全性不高

Default.aspx中頁面html

<%@ Page Title="主頁" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript" language="javascript">
        function GetJson() {
            $.ajax({
                type: "POST",
                url: "About.aspx/GetJsonData",
                contentType: "application/json;charset=utf-8",
                //data: "{t:'" + document.getElementById("inputText").value + "'}",
                success: function (data) {
                    debugger;
                    var s = data.d;
                    alert(s);
                }
            })
         }
    </script>
    <h2>
        歡迎使用 ASP.NET!
    </h2>
    <p>
        若要了解關於 ASP.NET 的詳細資訊,請訪問 <a href="http://www.asp.net/cn" title="ASP.NET 網站">www.asp.net/cn</a>。
    </p>
    <p>
        您還可以找到 <a href="http://go.microsoft.com/fwlink/?LinkID=152368"
            title="MSDN ASP.NET 文件">MSDN 上有關 ASP.NET 的文件</a>。
    </p>
    <input type="text" id="inputText" /><input type="button" value="提交" onclick="GetJson();" />
</asp:Content>

 

在About.aspx中新增方法

public partial class About : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [System.Web.Services.WebMethod] //必須新增次引用,不然無法訪問
        public static object GetJsonData()
        {
            object obj = new  { id=2,name="name" };
            return obj;
        }
    }

 

相關文章