asp.net mvc 服務器端返回JSON
廣告:
using System;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
using System.Drawing;
#region 生成文件JSON(也可直接輸出JSON,生成文件便于減少服務器壓力)
public void Provincefile()
{
int classid = 1; //報紙 6為雜志
if (Request.QueryString["bi"] != null && Request.QueryString["bi"].ToString() != "")
classid = int.Parse(Request.QueryString["bi"].ToString());
string wherestr = " parentid=0 ";
string sql = "select areaid,cnname,parentid,childclass from area where " + wherestr;
SqlDataReader dr = DB.DataReader(sql, null);
string areaid = "";
string cnname = "";
int total = 0;
int i = 0;
int j = 0;
string childclass = "";
StringBuilder hb = new StringBuilder();
hb.Append("{\"bk_province\": [ ");//返回bk_province表
while (dr.Read())
{
i++;
areaid = dr[0].ToString();
cnname = dr[1].ToString();
total = Mvc_areabll.Totalbk(Fun.Toint(areaid),classid);
childclass=dr[3].ToString();
if (i >1)
hb.Append(",");
hb.Append("{ \"areaid\": \"");
hb.Append(areaid);
hb.Append("\", \"cnname\": \"");
hb.Append(cnname);
hb.Append("\", \"total\": \"");
hb.Append(total);
hb.Append("\", \"childclass\": \"");
hb.Append(childclass);
hb.Append("\"");
//下面二級城市 bk_city:{....}
wherestr = " parentid=" +areaid;
sql = "select areaid,cnname,parentid,childclass from area where " + wherestr;
SqlDataReader dr2 = DB.DataReader(sql, null);
j = 0;
if (dr2.Read())
{
hb.Append(",\"bk_city\": [ ");//二級bk_city表記錄
do
{
areaid = dr2[0].ToString();
cnname = dr2[1].ToString();
total = Mvc_areabll.Totalbk(Fun.Toint(areaid), classid);
childclass = dr2[3].ToString();
if (total > 0)
{
j++;
if (j>1)
hb.Append(",");
hb.Append("{ \"cityid\": \"");
hb.Append(areaid);
hb.Append("\", \"cityname\": \"");
hb.Append(cnname);
hb.Append("\", \"citytotal\": \"");
hb.Append(total);
hb.Append("\", \"citychildclass\": \"");
hb.Append(childclass);
hb.Append("\" }");
}
}
while (dr2.Read());
hb.Append(" ]"); //二級bk_city表記錄
}
dr2.Close();
dr2.Dispose();
//二級城市 bk_city finish
hb.Append(" }");
}
dr.Close();
dr.Dispose();
hb.Append(" ] }"); //返回表名
string filestr = hb.ToString();
//生成json文件
string filename = "";
if (classid == 1)
filename = "bk_province.json";
else
filename = "mag_province.json";
string filename1 = Server.MapPath(Fun.Webdirectory + Fun.Savedata() + "/json/" + filename);
// Response.Write(filestr);
Mvccom.Funs.SaveFile(filestr, filename1);
Response.Write("ok");
hb = null;
return;
}
#endregion
using System;
using System.Globalization;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
#region 保存為文件方法
public static void SaveFile(string filecon, string fileName)
{
FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
byte[] byteData = Encoding.UTF8.GetBytes(filecon);
fs.Write(byteData, 0, byteData.Length);
fs.Close();
fs.Dispose();
}
#endregion
廣告: