I cannot get how I can return JSON data with my code.
JS
$(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetProducts",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// How to return data here like a table???
$("#Second").text(msg.d);
//alert(msg.d);
}
});
});
C# of Default.aspx.cs
[WebMethod]
public static string GetProducts()
{
var products = context.GetProducts().ToList();
return What do I have to return ????
}
Thanks in advance!
This question is related to
c#
javascript
jquery
asp.net
ajax
This structure works for me - I used it in a small tasks management application.
The controller:
public JsonResult taskCount(string fDate)
{
// do some stuff based on the date
// totalTasks is a count of the things I need to do today
// tasksDone is a count of the tasks I actually did
// pcDone is the percentage of tasks done
return Json(new {
totalTasks = totalTasks,
tasksDone = tasksDone,
percentDone = pcDone
});
}
In the AJAX call I access the data like this:
.done(function (data) {
// data.totalTasks
// data.tasksDone
// data.percentDone
});
Asp.net is pretty good at automatically converting .net objects to json. Your List object if returned in your webmethod should return a json/javascript array. What I mean by this is that you shouldn't change the return type to string (because that's what you think the client is expecting) when returning data from a method. If you return a .net array from a webmethod a javaScript array will be returned to the client. It doesn't actually work too well for more complicated objects, but for simple array data its fine.
Of course, it's then up to you to do what you need to do on the client side.
I would be thinking something like this:
[WebMethod]
public static List GetProducts()
{
var products = context.GetProducts().ToList();
return products;
}
There shouldn't really be any need to initialise any custom converters unless your data is more complicated than simple row/col data
Try to use this , it works perfectly for me
//
varb = new List<object>();
// Example
varb.Add(new[] { float.Parse(GridView1.Rows[1].Cells[2].Text )});
// JSON + Serializ
public string Json()
{
return (new JavaScriptSerializer()).Serialize(varb);
}
// Jquery SIDE
var datasets = {
"Products": {
label: "Products",
data: <%= getJson() %>
}
Just return object: it will be parser to JSON.
public Object Get(string id)
{
return new { id = 1234 };
}
Source: Stackoverflow.com