c# - Post方法json数据并在aspx文件中接收

标签 c# jquery asp.net json ajax

您好,我正在使用 jQuery AJAX 将数据发送到我的 aspx 文件。这是我的 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);
            }
        });
    });
});

我的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();
        }
    }
}

但我不断收到此错误:

System.ArgumentOutOfRangeException

An exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll but was not handled in user code

Additional information: Index was out of range. Must be non-negative and less than the size of the collection.

最佳答案

1.首先需要更改data参数以指向id变量:

data: {"videoid": id}

2.其次,不要使用:

字符串查询 = Request.QueryString[0];

使用

字符串查询 = Request.Form["videoid"];

3.不幸的是,即使您进行了上述两项更改,您的数据绑定(bind)逻辑也将无法工作。您无法通过创建 AJAX 来设置 GridView 控件的数据源打电话。

而是更改您的代码以使用服务器端单击事件或更改您的服务器逻辑以将数据返回到 AJAX 函数,循环遍历它并使用 jQuery 将其附加到 GridView。示例 - Binding GridView using AJAX .

隐藏代码:

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:

<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>

输出:

Bind GridView using AJAX

关于c# - Post方法json数据并在aspx文件中接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38280636/

相关文章:

asp.net - 使用 StateServer 时如何查找活跃用户数

c# - ASP .NET Core 2 本地化获取新语言的所有字符串

c# - 你必须刷新你的 BinaryWriter 数据吗

C# VSTO 展望 2007 : How to show contact by EntryID

c# - ASP.NET WebForms 设计模式

c# - 使用自动映射器对对象层次结构进行非规范化

javascript - 使用 Jquery 切换 div

javascript - 获取请求无法正常工作

Javascript 固定页脚覆盖焦点

c# - 在 EF Code First DatabaseIntializer 中重用 GUID