38

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 ????
}
starball
58.2k50 gold badges299 silver badges1k bronze badges
asked Aug 15, 2013 at 0:54
4
  • 1
    why don't you use web api? Commented Aug 15, 2013 at 0:56
  • 2
    Try the JavaScriptSerializer class. Commented Aug 15, 2013 at 0:58
  • Take a look at this question: stackoverflow.com/questions/8405458/… Basically, you need to return a json string and for that, you need to use JavaScriptSerializer to serialize C# objects/lists into json strings. You're not far. Commented Aug 15, 2013 at 1:36
  • 1
    .NET auto-serializes many types... including 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> Commented Aug 15, 2013 at 16:06

5 Answers 5

39

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.

answered Aug 15, 2013 at 1:41
4
  • 5
    you can also add this on top of your static method with JavaScriptSerializer [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] Commented Aug 15, 2013 at 8:12
  • 1
    What 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. Commented Aug 19, 2013 at 13:47
  • 1
    If 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/… Commented Aug 19, 2013 at 15:26
  • 1
    And this one too: stackoverflow.com/questions/8460458/… Commented Aug 19, 2013 at 15:26
14

Just return object: it will be parser to JSON.

public Object Get(string id)
{
 return new { id = 1234 };
}
answered Nov 3, 2015 at 7:19
2
  • Very short and sweet ! Great idea. Commented Mar 15, 2017 at 21:31
  • 1
    it returns "[object Object]". How do you decorate things to make it automatically return json? Commented Mar 1, 2019 at 4:43
6

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
});
answered Oct 8, 2015 at 15:27
2

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

answered Aug 15, 2013 at 0:59
-7

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() %> 
 }
answered Aug 15, 2013 at 13:28

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.