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 ????
}
5 Answers 5
You're not far; you need to do something like this:
[WebMethod]
public static string GetProducts()
{
// instantiate a serializer
JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
//optional: you can create your own custom converter
TheSerializer.RegisterConverters(new JavaScriptConverter[] {new MyCustomJson()});
var products = context.GetProducts().ToList();
var TheJson = TheSerializer.Serialize(products);
return TheJson;
}
You can reduce this code further but I left it like that for clarity. In fact, you could even write this:
return context.GetProducts().ToList();
and this would return a json string. I prefer to be more explicit because I use custom converters. There's also Json.net but the framework's JavaScriptSerializer
works just fine out of the box.
-
5you can also add this on top of your
static method
withJavaScriptSerializer
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
Ali Umair– Ali Umair2013年08月15日 08:12:01 +00:00Commented Aug 15, 2013 at 8:12 -
1What is
MyCustomJson
supposed to be here? Can you provide a link to an example? I'm wondering how much manual coding is going to be necessary for a given class.Justin Morgan– Justin Morgan2013年08月19日 13:47:57 +00:00Commented Aug 19, 2013 at 13:47 -
1If you don't have a custom converter, the serializer will serialize/deserialize your C# object to json with the same properties name. But if you want your javascript object to be different from you C# object, or want to include some validation rules when you deserialize, then you need a custom converter. Here are some questions I asked about that: stackoverflow.com/questions/4998595/… stackoverflow.com/questions/10193024/…frenchie– frenchie2013年08月19日 15:26:05 +00:00Commented Aug 19, 2013 at 15:26
-
1And this one too: stackoverflow.com/questions/8460458/…frenchie– frenchie2013年08月19日 15:26:23 +00:00Commented Aug 19, 2013 at 15:26
Just return object: it will be parser to JSON.
public Object Get(string id)
{
return new { id = 1234 };
}
-
Very short and sweet ! Great idea.Sandip Subedi– Sandip Subedi2017年03月15日 21:31:28 +00:00Commented Mar 15, 2017 at 21:31
-
1it returns "[object Object]". How do you decorate things to make it automatically return json?PepitoSh– PepitoSh2019年03月01日 04:43:21 +00:00Commented Mar 1, 2019 at 4:43
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() %>
}
JavaScriptSerializer
class.List<object>
,Dictionary<string, object>
, etc. If you structure your classes in such a way as to be useful when serialized, you don't even have to do anything fancy, just make your return type (in this case)List<Product>