skip to Main Content

I am trying to pass some data to client side using ajax, but can’t do it succesfully. I get error in browser failed to load resource. I checked jQuery is loaded correctly.

[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;
        }
        
    }

This is my c# code. It is placed in controller named HomeController.cs.

Here is my js script:

$(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");
    }
});

})

I am trying to pass data from asp.net webforms and i am using .net framework 4.5. I am trying just to send data for now and i will worry about other thins when i successfuly send it.

3

Answers


  1. test it after adding this in your ajax property,

            type: 'GET',
            url: '/Home/GetGraphData',                
            dataType: "json",
            ContentType: "application/json;charset=utf-8",
    
    Login or Signup to reply.
  2.  $(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");
            }
        });
        
        })
    
    Login or Signup to reply.
  3. Well, you get a huge award for introductiong the term and concept and name "controler" when you are using web forms. (getting paid to confuse people here???).

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

    You can either:

    Create a new seperate web page (asmx page), OR YOU can add some web methods to your existing web form page.

    So, markup will be this:

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

    code behind on this same web form page:

        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);
        }
    

    And we run, and get this:

    enter image description here

    Now, NOTE how I set the data type of that function to return a string.

    I could return a serialized object – change "string" of the function to int[,] and we can return that object.

    So, say this:

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

    So, now that we set the type of the function, then return will AUTOMATIC serlize to the object type int[,]

    At this point, then client side code could reverse the object back to a string.

    eg this:

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

    And now we get this:

    enter image description here

    so result.d (d means data return) is the result.

    but, if we remove the json.Stringify, then we have a js object.

    eg this:

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

    And now this:

    enter image description here

    Also note:

    the page method is public STATIC. This is because you calling webmethod. that means you don’t have use of controls on the page, no post-back, and hence no class instance of the page object. You cant use viewstate either (but, you can use session).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search