【问题标题】:Can I use JSON.Stringify in code-behind of an ASP.Net project?我可以在 ASP.Net 项目的代码隐藏中使用 JSON.Stringify 吗?
【发布时间】:2017-07-09 15:50:52
【问题描述】:

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

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

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

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

所以我在presenter中设置了:

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 = "";
       }
   }
}

【问题讨论】:

  • 只是发布您尝试过的内容的 sn-p 吗?
  • 好的,我编辑了我的解释并添加了我项目中的一些示例。
  • GetContentAsJson(uuid) 返回什么?
  • 不,它只是一个用于获取数据的字符串变量。该数据用于创建 JSON 的内容。

标签: c# asp.net json


【解决方案1】:

JSON.stringify()实际上是将JavaScript对象转换为字符串,您可以在服务器端这样做:

using System.Web.Script.Serialization;

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

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

【讨论】:

    【解决方案2】:

    你可以使用类似的东西

    JsonConvert.SerializeObject(ob)
    

    来自库:Newtonsoft.Json

    【讨论】:

      猜你喜欢
      • 2010-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-29
      相关资源
      最近更新 更多