简体   繁体   English

发布方法json数据并在aspx文件中接收

[英]Post method json data and receive in aspx file

Hello I'm using jQuery AJAX to send a data to my aspx file. 您好,我正在使用jQuery AJAX将数据发送到我的aspx文件。 Here is my AJAX: 这是我的AJAX:

$(document).ready(function() {
    $('#openmodal').click(function() {
        var id = $(this).attr('data-id');
        $.ajax({
            type: "POST",
            url: "Video.aspx",
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            data: {
                "videoid": "id"
            },
            dataType: "json",
            success: function(resultData) {
                console.log(resultData);
            },
            error: function(errordata) {
                console.log(errordata);
            }
        });
    });
});

My aspx.cs 我的aspx.cs

protected void Page_Load(object sender, EventArgs e) {
    string query = Request.QueryString[0];
    if (query != null) {
        if (!IsPostBack) {
            gvShow.DataSource = VideoBL.GetVideo(query);
            gvShow.DataBind();
        }
    }
}

But I keep getting this error: 但我不断收到此错误:

System.ArgumentOutOfRangeException System.ArgumentOutOfRangeException

An exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll but was not handled in user code mscorlib.dll中发生类型为'System.ArgumentOutOfRangeException'的异常,但未在用户代码中处理

Additional information: Index was out of range. 附加信息:索引超出范围。 Must be non-negative and less than the size of the collection. 必须为非负数并且小于集合的大小。

1.Firstly you need to change the data parameter to point to the id variable: 1.首先您需要更改data参数以指向id变量:

data: {"videoid": id}

2.Secondly, instead of using: 2.其次,不要使用:

string query = Request.QueryString[0];

use 采用

string query = Request.Form["videoid"];

3.Unfortunately even after you made the two changes above your data binding logic will not work .You cannot set a data source of the GridView control by making an AJAX call. 3.不幸的是,即使在上面的两个更改之后,数据绑定逻辑也无法使用 。您无法通过调用AJAX来设置GridView控件的数据源。

Rather change your code to use a server side click event OR change your server logic to return the data back to the AJAX function,loop through it and append it to the GridView using jQuery.Here's an example - Binding GridView using AJAX . 而不是更改代码以使用服务器端单击事件,或者更改服务器逻辑以将数据返回到AJAX函数,循环遍历并使用jQuery将其附加到GridView这里是一个示例- 使用AJAX绑定GridView

Code behind: 后面的代码:

public class MyVideo
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public partial class Video : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            gvShow.DataSource = new List<MyVideo> { new MyVideo { ID = 0, Name = "Initial..." } };
            gvShow.DataBind();
        }
    }

    [System.Web.Services.WebMethod]
    public static List<MyVideo> GetVideos(string videoid)
    {
        MyVideo v1 = new MyVideo { ID = 1, Name = "Video 1" };
        MyVideo v2 = new MyVideo { ID = 1, Name = "Video 2" };
        MyVideo v3 = new MyVideo { ID = 3, Name = "Video 3" };

        var videos = new List<MyVideo> { v1, v2, v3 };
        return videos.Where(v => v.ID == 1).ToList();//Hardcoding for simplicity
    }
}

.ASPX: .ASPX:

<head runat="server">
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script type="text/javascript">
        $(function () {
            $('#modal').click(function () {
                var id = $(this).attr('data-id');

                $.ajax({
                    type: "POST",
                    url: "Video.aspx/GetVideos",
                    contentType: "application/json;charset=utf-8",
                    data: '{videoid:"' + id + '"}',
                    dataType: "json",
                    success: function (data) {
                        var videos = data.d;
                        $("#gvShow").empty();

                        for (var i = 0; i < videos.length; i++) {
                            var id = videos[i].ID;
                            var name = videos[i].Name;
                            var tr = "<tr><td>" + id + "</td><td>" + name + "</td></tr>"
                            $("#gvShow").append(tr);
                        }
                        $('#myModal').modal('show');
                    },
                    error: function (errordata) {
                        console.log(errordata);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <a href="#" id="modal" data-id="2">Click me</a>
        <div id="myModal" class="modal fade">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title">Videos</h4>
                    </div>
                    <div class="modal-body">
                        <asp:GridView ID="gvShow" runat="server">
                        </asp:GridView>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    </form>
</body>

Output: 输出:

使用AJAX绑定GridView

In this javascript line 在此javascript行中

data: { "videoid": "id" },

you send the string "id" , not the number that contains the id. 您发送字符串"id" ,而不是包含ID的数字。

So in this line 所以在这一行

 gvShow.DataSource = VideoBL.GetVideo(query);

you probably call 你可能会打电话

 gvShow.DataSource = VideoBL.GetVideo("id");

or call it with empty string 或用空字符串调用

 gvShow.DataSource = VideoBL.GetVideo("");

or I don't know what you actually send there, and there you get the error message. 或者我不知道您实际发送到那里,然后收到错误消息。

Advice, debug your code line by line... and you find all that errors and how to correct them 建议,逐行调试代码...,您会发现所有错误以及如何纠正它们

I think the problem is that you are trying to get data from request query string where your data is posted to the server as a form, you can try to get your posted data using 我认为问题在于您正在尝试从请求查询字符串中获取数据,其中您的数据以表单的形式发布到服务器,您可以尝试使用以下方法获取发布的数据:

string query = Request["videoid"];

This will get data from the cookies, form, query string or server variables. 这将从cookie,表单,查询字符串或服务器变量中获取数据。 or you can get your data from the posted form only using 或者您只能使用以下方式从发布的表单中获取数据

string query = Request.Form["videoid"];

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

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