In development, sometimes we need to get the model return data in the view layer and be a Json object, then we can take advantage of the Newtonsoft.Json.JsonConvert.SerializeObject (model) The model layer is deserialized, since JS gets deserialized data after some special characters need to be processed, such as: double quotation marks "will become " after deserialization, so to replace it with", Str.replace (/"/g, "\" "), And then use the JS function json.parse to convert it, you get a JSON object
Background C # code:
Namespacemvcapplication1.controllers{PublicClassHomecontroller:controller {PublicActionResult Index () {View_news view_news =NewView_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;ReturnView (view_news); } }PublicClassview_news {public list<news> newslist {get; set;}} public class News {public string Url {get; set;} public string Image {get; Span style= "COLOR: #0000ff" >set;} public string Title {get; Span style= "COLOR: #0000ff" >set
Front Code:
@model mvcapplication1.controllers.view_news@{Layout = null; String str = Newtonsoft.Json.JsonConvert.SerializeObject (model.newslist);}<!DOCTYPE html><Html><Head><MetaName= "Viewport"Content= "Width=device-width"/><Title>index</Title><ScriptSrc= "~/scripts/jquery-1.8.2.min.js"></Script><ScriptType= "Text/javascript">VarPicdata={};VarTheString=‘@ (str)‘= Thestring.replace (/" /g, "\" " ); var temp = Json.parse (thestring); Picdata.news = temp; Console.log (picdata); </script> </head>
Output Result:
MVC model Turn JSON