C#集合转换为json

一、C#代码

using MakeTreeData.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace MakeTreeData.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
TreeDataEntities treeDataEntities = new TreeDataEntities();
//List<CatalogPo> catalogsList = null;
//catalogsList = treeDataEntities.Catalogs.Select(c => c.ToPo()).ToList();
List<Catalog> catalogsList = treeDataEntities.Catalogs.ToList();

JavaScriptSerializer jsc = new JavaScriptSerializer();

System.Text.StringBuilder jsonData = new System.Text.StringBuilder();
jsc.Serialize(catalogsList, jsonData);
ViewBag.treeData = jsonData ;
return View();
}
[HttpPost]
public ActionResult Index(FormCollection form)
{
TreeDataEntities treeDataEntities = new TreeDataEntities();

List<Catalog> catalogsList = treeDataEntities.Catalogs.ToList();

JavaScriptSerializer jsc = new JavaScriptSerializer();

System.Text.StringBuilder jsonData = new System.Text.StringBuilder();
jsc.Serialize(catalogsList, jsonData);

return Json(jsonData);
}

}
}

 

二、js代码

@{
Layout = null;
}

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div >
@ViewBag.treeData
</div>
</div>

<script type="text/javascript">

data = "@ViewBag.treeData";

$(function () {
//alert(data);
data = data.replace(/&quot;/g, "\"");//&quot;
data = "{\"d\":" + data + "}";
treeData = $.parseJSON(data);
for (var i = 0; i < treeData.d.length; i++) {
var ID = treeData.d[i].ID;
var Name = treeData.d[i].Name;
alert(ID+"===="+Name)
}
});
</script>
</body>
</html>

你可能感兴趣的:(C#集合转换为json)