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
test it after adding this in your ajax property,
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:
code behind on this same web form page:
And we run, and get this:
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:
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:
And now we get this:
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:
And now this:
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).