Convert List to Json Result in ASP.NET MVC

Convert List to Json result, return type as JsonResult.
public JsonResult CountryList()
{
    List<Country> countries = Country.GetCountries();
    return Json(countries, JsonRequestBehavior.AllowGet);
}

Now to consume same result in Ajax responce we have to use JSON.parse

success: function (data) {
    data = JSON.parse(data);
    for (var i = 0; i < data.length; i++) {
        if (data[i] != '') {
            // here you will get each item of list as data[i]
        }
    }
},

on the same, How two return multiple list in Json.
Controller method

public JsonResult CountryList()
{
    List<Country> countries = Country.GetCountries();
    List<State> state = State.GetCountries();
    return Json(new { Countries = countries , State = state}, JsonRequestBehavior.AllowGet);
}

Now get two list in ajax response

success: function (data) {
    data = JSON.parse(data);
    for (var i = 0; i < data.Countries.length; i++) {
        if (data.Countries[i] != '') {
            // here you will get each item of list as data[i]
        }
    }
    for (var i = 0; i < data.State.length; i++) {
        if (data.State[i] != '') {
            // here you will get each item of list as data[i]
        }
    }
},
Advertisements
This entry was posted in jQuery, MVC and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s