Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Json data from MVC controller

   public ActionResult About()
    {
        List<Stores> listStores = new List<Stores>();
        listStores = this.GetResults("param");
        return Json(listStores, "Stores", JsonRequestBehavior.AllowGet);
    }

Using the above code I am able to get the below result

[{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555","email":"[email protected]","geo":{"latitude":"12.9876","longitude":"122.376237"}},

{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454","email":"[email protected]","geo":{"latitude":"12.9876","longitude":"122.376237"}},

How would I able to get the result in below format?

{

"stores" : [
{"id":"1","name":"Store1","cust_name":"custname1","telephone":"1233455555","email":"[email protected]",
"geo":{"latitude":"12.9876","longitude":"122.376237"}},

{"id":"2","name":"Store2","cust_name":"custname2","telephone":"1556454","email":"[email protected]","geo":{"latitude":"12.9876","longitude":"122.376237"}} ] 
}

I would like to have the stores at the beginning of the data.

Please help me in this regard.

like image 997
user557211 Avatar asked Mar 28 '26 21:03

user557211


2 Answers

You will need to create an object that contains the stores within a property named stores:

public ActionResult About()
{
    var result = new { stores = this.GetResults("param") };
    return Json(result, "Stores", JsonRequestBehavior.AllowGet);
}

I've used an anonymous type for simplicity here, if this result type were required in multiple places you may consider creating a 'proper' class for it.

like image 69
Rich O'Kelly Avatar answered Mar 31 '26 09:03

Rich O'Kelly


JavaScriptSerializer can be found from namespace System.Web.Script.Serialization

var ser = new JavaScriptSerializer();
var jsonStores = ser.Serialize(stores);

return Json(new { stores: jsonStores }, "Stores", JsonRequestBehavior.AllowGet);
like image 28
Tx3 Avatar answered Mar 31 '26 08:03

Tx3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!