首页 > Web开发 > 详细

MVC之Model转Json

时间:2018-03-13 14:33:20      阅读:175      评论:0      收藏:0      [点我收藏+]

在开发中,有时我们需要在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(/&quot;/g,"\"");
        var temp = JSON.parse(theString);
        picData.news = temp;
        console.log(picData);
    </script>
</head>
技术分享图片

输出结果:

技术分享图片

MVC之Model转Json

原文:https://www.cnblogs.com/zhangruisoldier/p/8556153.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!