Sai Avinash
Sai Avinash

Reputation: 4753

How to get extended json response from ASP.net controller method

I am working on ASP.net MVC Applciation

I am facing difficulty in preparing json response to return from a controller action method.

I need some thing like this:

{
    "cityMap": {"11": "Chennai", "12": "Mumbai", "13": "Delhi"},
    "rows": [
        { "SID": "1",  "SNAME": "ABC", "CITY": "11" },
        { "SID": "2",  "SNAME": "XYZ", "CITY": "12" },
        { "SID": "3",  "SNAME": "ACX", "CITY": "13" },
        { "SID": "4",  "SNAME": "KHG", "CITY": "13" },
        { "SID": "5",  "SNAME": "ADF", "CITY": "12" },
        { "SID": "6",  "SNAME": "KKR", "CITY": "11" }
    ]
}

I have cityMap values in the sortedlist names slLocations

I have row values in the form of list liStudents

I am using the following syntax to send the json response:

return JSON(new { rows=liStudents},jsonRequestBehaviour.AllowGet)

By using the above syntax , i am getting the json response like this:

 {
  "rows": [
            { "SID": "1",  "SNAME": "ABC", "CITY": "11" },
            { "SID": "2",  "SNAME": "XYZ", "CITY": "12" },
            { "SID": "3",  "SNAME": "ACX", "CITY": "13" },
            { "SID": "4",  "SNAME": "KHG", "CITY": "13" },
            { "SID": "5",  "SNAME": "ADF", "CITY": "12" },
            { "SID": "6",  "SNAME": "KKR", "CITY": "11" }
        ]
  }

Please help on how to extend json response to above by using liStudents and liLocations

Upvotes: 0

Views: 95

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

Simply add the desired cityMap property to the anonymous object that you are passing to the view:

var model = new
{
    cityMap = slLocations,
    rows = liStudents,
}
return JSON(model, JsonRequestBehaviour.AllowGet);

This obviously assumes that the slLocations variable is a SortedList<string, string>.

Upvotes: 1

Related Questions