MVC model Turn JSON

Source: Internet
Author: User

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 &quot 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 (/&quot; /g, "\" " ); var temp = Json.parse (thestring); Picdata.news = temp; Console.log (picdata); </script> </head>   

Output Result:

MVC model Turn JSON

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.