我可以在ASP.Net项目的代码隐藏中使用JSON.Stringify

时间:2017-02-20 11:27:48

标签: c# asp.net json

在ASP.NET项目(MVP模式)的代码隐藏中,我在其中一个演示者中得到一个字符串,其中包含类似于JSON文件内容的内容。

然后我使用该字符串设置视图的一个属性 - 分配给演示者。

在视图中,字符串显示在TextBox中,但看起来不太好,因为它没有使用换行符和换行符进行结构化。 我知道有一个名为Stringify的JSON函数可以使这些字符串变得漂亮。

我可以在代码隐藏中调用JSON函数吗? 每个例子我在演示者中设置视图的属性?

所以我在演示者中设置了它:

this.view.ContentAsJson = GetContentAsJson(uuid);

这是我想做的,如果可能的话:

this.view.ContentAsJson = JSON.Stringify(GetContentAsJson(uuid));

GetContentAsJson是一个创建并返回JSON字符串的函数。

这是我的观点:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ContentJsonView.ascx.cs" Inherits="WebCenter.PP.PI.WebGui.View.FolderView.ContentJsonView" %>
<%@ Import Namespace="WebCenter.PP.Common.Domain" %>
<div id="DivContentJson" class="clearfix">
    <p>
        <asp:TextBox runat="server" ID="TbContentJson" TextMode="MultiLine" Height="100%" Width="100%" />
    </p>
</div>

这是视图中获取字符串的属性:

public string ContentAsJson
{
   set
   {
       if (!string.IsNullOrEmpty(value))
       {
            TbContentJson.Text = value;
       }
       else
       {
            TbContentJson.Text = "";
       }
   }
}

2 个答案:

答案 0 :(得分:19)

JSON.stringify()实际上将JavaScript对象转换为字符串,您可以在服务器端执行此操作:

using System.Web.Script.Serialization;

var json = new JavaScriptSerializer().Serialize(obj);

编辑:JSON.stringify()是客户端(浏览器)功能。所以你不能在服务器端这样做。

答案 1 :(得分:4)

您可以使用

之类的东西
JsonConvert.SerializeObject(ob)

来自库:Newtonsoft.Json

相关问题