如何从IQueryable的WebMethod返回JSON?

时间:2014-11-11 00:49:20

标签: c# json webmethod

我正在尝试从IQueryable的web方法返回JSON,但是我没有使用JSON获取HTML。
WebMethod必须使用UseHttpGet = true签名。
这必须使用子节点创建JSON:国家/地区节点(ID,CountryName)>区域节点(RegionID,RegionName)>城市节点(CityID,CityName) 这是代码:

[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;
}

以下是模型:

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; }
}

1 个答案:

答案 0 :(得分:1)

这就是我有一个返回JSon的简单方法

using System.Web.Script.Serialization;
//declared at the class level is my DataClassesDataContext 
DataClassesDataContext dc = new DataClassesDataContext();

[WebMethod (Description = "Get Strapping by passing StapKeyId") ]
public string GetStrapping(string strapKeyId)
{
    var json = string.Empty;
    var railcar = from r in dc.tblRailcars
                  join s in dc.tblStraps on r.TankStrapping_KeyID equals s.KeyId
                  where r.TankStrapping_KeyID == Int32.Parse(strapKeyId)
                  select new 
                  { 
                      r.RailcarMark, 
                      r.RailcarNumber,
                      r.TankStrapping_KeyID,
                      s.Capacity,
                      s.TableNumber,
                      s.TableType
                  };

   JavaScriptSerializer jss = new JavaScriptSerializer();
   json = jss.Serialize(railcar);

    return json;
}

//如果您想通过使用字典来查看其他方法,请在此处链接到我去年发布的内容 Deserialize a Dynamic JSON Array on C#