首页 > 代码库 > MVC之Model转Json
MVC之Model转Json
在开发中,有时我们需要在View层中拿到Model返回的数据并且是一个Json对象,那么我们就可以利用Newtonsoft.Json.JsonConvert.SerializeObject(Model)将Model层反序列化,由于js拿到反序列化的数据后一些特殊字符还需要处理,如:双引号"反序列化后会变成",所以要将其替换成",str.replace(/"/g,"\""),然后再用js函数JSON.parse将其转换,就得到一个Json对象
后台C#代码:
namespace MvcApplication1.Controllers { public class HomeController : Controller { public ActionResult Index() { View_News View_News = new View_News(); List<News> NewsList = new List<News>(); NewsList.Add(new News() { Url = "www.baidu.com", Image = "/Resource/Skin02", Title = "Tom" }); NewsList.Add(new News() { Url = "www.taobao.com", Image = "/Resource/Skin03", Title = "Jim" }); NewsList.Add(new News() { Url = "www.jd.com", Image = "/Resource/Skin04", Title = "Jess" }); View_News.NewsList = NewsList; return View(View_News); } } public class View_News { public List<News> NewsList { get; set; } } public class News { public string Url { get; set; } public string Image { get; set; } public string Title { get; set; } } }
前台代码:
@model MvcApplication1.Controllers.View_News @{ Layout = null; string str = Newtonsoft.Json.JsonConvert.SerializeObject(Model.NewsList); } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script src="~/Scripts/jquery-1.8.2.min.js"></script> <script type="text/javascript"> var picData = {}; var theString = ‘@(str)‘; theString = theString.replace(/"/g,"\""); var temp = JSON.parse(theString); picData.news = temp; console.log(picData); </script> </head>
输出结果:
MVC之Model转Json
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。