I'm trying to return JSON from the webmethod of IQueryable but instead of JSON I'm getting HTML.
WebMethod must be with UseHttpGet=true signature.
This must create JSON with child nodes: Country node (ID, CountryName) > Region node (RegionID, RegionName) > City node (CityID, CityName)
Here is the code:
[System.Web.Services.WebMethod(BufferResponse = false)]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json, UseHttpGet=true)]
public static IQueryable<CountryModel> GenerateJson()
{
RudenSoftEntities db = new RudenSoftEntities();
var a = from country in db.Countries
select new CountryModel
{
ID = country.Id,
CountryName = country.CountryName,
_region = (from region in db.Regions
where region.CountryID == country.Id
select new RegionModel
{
RegionID = region.Id,
RegionName = region.RegionName,
_city = (from city in db.Cities
where city.RegionID == region.Id
select new CityModel
{
CityID = city.Id,
CityName = city.CityName
}).ToList()
}).ToList()
};
return a;
}
And here is the model:
public class CountryModel
{
public int ID { get; set; }
public string CountryName { get; set; }
public List<RegionModel> _region = new List<RegionModel>();
}
public class RegionModel
{
public int RegionID { get; set; }
public string RegionName { get; set; }
public List<CityModel> _city = new List<CityModel>();
}
public class CityModel
{
public int CityID { get; set; }
public string CityName { get; set; }
}
This is how I have a simple method that returns JSon
//If you want to see an additional way of doing it by using a Dictionary here is a link to what I have posted last year as well Deserialize a Dynamic JSON Array on C#