SmackDat SmackDat - 5 months ago 16
JSON Question

Post method json data and receive in aspx file

Hello I'm using jQuery AJAX to send a data to my aspx file. Here is my AJAX:

$(document).ready(function() {
$('#openfuckingmodal').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

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

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.

Answer

1.Firstly you need to change the data parameter to point to the id variable:

data: {"videoid": id}

2.Secondly, instead of using:

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.

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.

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:

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

Bind GridView using AJAX