0

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 3

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much, i will try this later. I am really new to this, I just started learning.
I now get System.InvalidOperationException, can you help me with that also? Sorry for bothering you.
The code as posted works. Try creating a new blank web form page. Drop in the above markup. You have to change the page name used AjaxTest1.aspx/GetGraphData to MyTestPage/TheWebMethodGoesHere, and it should work. So, don't use a "/" in front, but just the name of your current web page. We assume the page has jQuery working. Example code posted is for webforms, and not MVC.
0

test it after adding this in your ajax property,

        type: 'GET',
        url: '/Home/GetGraphData',                
        dataType: "json",
        ContentType: "application/json;charset=utf-8",

2 Comments

I still dont get anything. The problem is, my action method in controller is never called.
if you using a controller, then this is not asp.net webforms, but sounds like this is a asp.net MVC project - there is VAST difference between the two types of projects. So, is this asp.net webform project, or is this a MVC. And if it is MVC, the you not using web forms, and the above examples will not apply then.
0
 $(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");
        }
    });
    
    })

1 Comment

This doesn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.