using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Script.Serialization; namespace MvcAppDemo.Controllers { public class UserController : Controller { private DBEntities db = new DBEntities(); /// <summary> /// 使用mvc Json序列化对象 /// </summary> /// <returns>返回是Json数据 数据类型:Json</returns> public ActionResult Index() { var list = db.UserInfo.ToList(); //如果action是get请求,要加上 JsonRequestBehavior.AllowGet 这个参数 return Json(list,JsonRequestBehavior.AllowGet); } // /// <summary> /// 使用mvc Json序列化对象 /// </summary> /// <returns>返回是Json数据 数据类型:Json</returns> [HttpPost] public ActionResult Demo() { var list = db.Account.ToList(); //如果action是post请求,可以不需要加上 JsonRequestBehavior.AllowGet 这个参数 return Json(list); } /// <summary> /// 使用mvc Json序列化对象 /// </summary> /// <returns>返回是Json数据 数据类型:Json</returns> [HttpPost] public ActionResult Demo2() { var list = db.Account.ToList(); //如果action是post请求,也可以加上 JsonRequestBehavior.AllowGet 这个参数 return Json(list,JsonRequestBehavior.AllowGet); } /*** * * 使用JavaScriptSerializer 序列化对象 * * ***/ /// <summary> /// 使用JavaScriptSerializer 序列化对象 /// </summary> /// <returns>返回是Json数据字符串 数据类型:string</returns> public ActionResult JSS() { var list = db.Account.ToList(); JavaScriptSerializer jss = new JavaScriptSerializer(); string content = jss.Serialize(list); //返回是json数据的字符串数据 return Content(content); } public ActionResult JSS2() { //将 Response.ContentType = "application/json"; 就变成json数据 Response.ContentType = "application/json"; var list = db.Account.ToList(); JavaScriptSerializer jss = new JavaScriptSerializer(); string content = jss.Serialize(list); //返回是json数据的字符串数据 return Content(content); } [HttpPost] public ActionResult JSS3() { var list = db.Account.ToList(); JavaScriptSerializer jss = new JavaScriptSerializer(); string content = jss.Serialize(list); //返回是json数据的字符串数据 return Content(content); } [HttpPost] public ActionResult JSS4() { //将 Response.ContentType = "application/json"; 就变成json数据 Response.ContentType = "application/json"; var list = db.Account.ToList(); JavaScriptSerializer jss = new JavaScriptSerializer(); string content = jss.Serialize(list); //返回是json数据的字符串数据 return Content(content); } } }