繁体   English   中英

无法使用 ajax 将数据从 asp.net 网络表单传递到客户端

[英]Can't pass data from asp.net webforms to client side using ajax

我正在尝试使用 ajax 将一些数据传递到客户端,但无法成功。 我在浏览器中收到错误无法加载资源。 我检查了 jQuery 是否正确加载。

[HttpGet]
    public string GetGraphData()
    {

        try
        {
            DataTable dt = new DataTable();
            int[,] datar = new int[,] { { 1, 10 }, { 2, 15 }, { 3, 13 }, { 4, 17 } };
            // create columns
            for (int i = 0; i < 2; i++)
            {
                dt.Columns.Add();
            }

            for (int j = 0; j < 4; j++)
            {
                // create a DataRow using .NewRow()
                DataRow row = dt.NewRow();

                // iterate over all columns to fill the row
                for (int i = 0; i < 2; i++)
                {
                    row[i] = datar[j, i];
                }

                // add the current row to the DataTable
                dt.Rows.Add(row);
            }

            string JsonString = JsonConvert.SerializeObject(dt);
            return JsonString;
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex);
            return null;
        }
        
    }

这是我的 c# 代码。 它位于名为 HomeController.cs 的 controller 中。

这是我的js脚本:

$(document).ready(function () {

$.ajax({

    type: 'GET',
    url: '/Home/GetGraphData',
    data: {},
    success: function (result) {
        alert("Data is here");
        console.log(result);
        
    },
    error: function (result) {
        alert("Data isnt here");
    }
});

})

我正在尝试从 asp.net 网络表单传递数据,并且我正在使用 .net 框架 4.5。 我现在只是尝试发送数据,当我成功发送数据时,我会担心其他问题。

好吧,当您使用 web forms 时,您会因为引入术语和概念以及名称“控制器”而获得巨额奖励。 (得到报酬来迷惑这里的人???)。

So, in web forms, you doing a ajax call, and that requires you to setup a web method to be called as ajax.

您可以:

创建一个新的单独的 web 页面(asmx 页面),或者您可以将一些 web 方法添加到现有的 web 表单页面。

所以,标记将是这样的:

        <br />
        <asp:Button ID="Button1" runat="server" Text="Web Service Call" 
            OnClientClick="myjava();return false"/>
        <br />
        <br />
        <asp:TextBox ID="TextBox2" runat="server" Height="245px" Width="704px"
            ClientIDMode="Static" TextMode="MultiLine"
            ></asp:TextBox>
        <br />
    </div>

    <script>
        function myjava() {
            // call web method in page
            $.ajax({
                type: "POST",
                url: "AjaxTest1.aspx/GetGraphData",
                data:{},
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (myresult) {
                    // put result of method call into txtResult
                    // ajax data is ALWAYS ".d" - its a asp.net thing!!!
                    $('#TextBox2').val(myresult.d)

                },
                error: function (xhr, status, error) {
                    var errorMessage = xhr.status + ': ' + xhr.statusText
                    alert('Error - ' + errorMessage)
                }
            });
        }
    </script>

在同一 web 表单页面上的代码后面:

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod()]
    public static string GetGraphData()
    {
        int[,] datar = new int[,] { { 1, 10 }, { 2, 15 }, { 3, 13 }, { 4, 17 } };
        return  JsonConvert.SerializeObject(datar);
    }

我们运行,得到这个:

在此处输入图像描述

现在,请注意我如何设置 function 的数据类型以返回字符串。

我可以返回一个序列化的 object - 将 function 的“字符串”更改为 int[,],我们可以返回该 object。

所以,这样说:

     [WebMethod()]
    public static int[,] GetGraphData()
    {
        int[,] datar = new int[,] { { 1, 10 }, { 2, 15 }, { 3, 13 }, { 4, 17 } };
        return  datar;
    }

所以,既然我们设置了 function 的类型,那么返回将 AUTOMATIC serlize 为 object 类型 int[,]

此时,客户端代码可以将 object 反转回字符串。

例如这个:

    $('#TextBox2').val(JSON.stringify(myresult.d))

现在我们得到了这个:

在此处输入图像描述

所以 result.d(d 表示数据返回)就是结果。

但是,如果我们删除 json.Stringify,那么我们有一个 js object。

例如这个:

    $('#TextBox2').val(myresult.d[1,1])

现在这个:

在此处输入图像描述

另请注意:

页面方法是 public STATIC。 这是因为您调用了 webmethod。 这意味着您没有使用页面上的控件,没有回发,因此没有页面 object 的 class 实例。 您也不能使用视图状态(但是,您可以使用会话)。

在您的 ajax 属性中添加后对其进行测试,

        type: 'GET',
        url: '/Home/GetGraphData',                
        dataType: "json",
        ContentType: "application/json;charset=utf-8",
 $(document).ready(function () {
    
    $.ajax({
    
        type: 'GET',
        url: '/Home/GetGraphData',                
        dataType: "json",
        ContentType: "application/json;charset=utf-8",
        data: {},
        success: function (result) {
            alert("Data is here");
            console.log(result);
            
        },
        error: function (result) {
            alert("Data isnt here");
        }
    });
    
    })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM