Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json object in C# .net

I have a C#.net method as given below

 public string jsonTest()
        {
            List<string> list = new List<string>();
            list.Add("aa");
            list.Add("bb");
            list.Add("cc");
            string output = JsonConvert.SerializeObject(list);
            return output;          
        }

Here eventhough Im creating a Json object by using JsonConvert.SerializeObject I am getting a string (since return type is string).

Can I do like below by using a return type JsonResult (or somthing like that) something like what we can do in MVC?

  return Json(new { data = list }, JsonRequestBehavior.AllowGet);

Is it possible to create a Json data in asp.net?

In client side I'm using an ajax call to get data from jsonTest().

  $.ajax({
                type: 'GET',
                url: "test.aspx",  //In test.aspx pageload calling jsonTest()
                dataType: 'json',
                success: function (data) {
                    alert(data);
                },
                error: function (data) {
                    alert("In error");
                }

            });

When I'm giving dataType: 'json', it will go to error part (Since the ajax expects json data but it gets string). Thats why I want to parse it as a json object in server side.

like image 438
Sudha Avatar asked Apr 17 '13 12:04

Sudha


1 Answers

If ASP.NET,

string output = JsonConvert.SerializeObject(list);
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(output);
Response.End();
like image 143
Dane Balia Avatar answered Sep 23 '22 21:09

Dane Balia