首页 > 代码库 > 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(/&quot;/g,"\"");
        var temp = JSON.parse(theString);
        picData.news = temp;
        console.log(picData);
    </script>
</head>

输出结果:

技术分享

 

MVC之Model转Json