Can I use JSON.Stringify in code-behind of an ASP.Net project?

In the code-behind of an ASP.NET project (MVP-pattern) I get in one of the presenters a string which contains something which looks like the content of a JSON file.

Then I set one of the properties of the view – which is assigned to the presenter – with that string.

In the view the string is displayed in a TextBox, but it doesn’t look good, because it is not structured with newlines and line feeds.
I know there is a JSON-function called Stringify which can make such strings pretty.

Can I call that JSON-function in code-behind?
Per example when I set the property of the view in the presenter?

So I set it in the presenter:

this.view.ContentAsJson = GetContentAsJson(uuid);

This is what I would like to do, if it’s possible:

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

GetContentAsJson is a function which creates and returns the JSON-string.

This is my view:

<%@ 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>

This is the property in the view which gets the string:

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use something like

JsonConvert.SerializeObject(ob)

From library: Newtonsoft.Json

Method 2

JSON.stringify() Actually converts a JavaScript object into a string, you can do it in server side like this:

using System.Web.Script.Serialization;

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

Edit: JSON.stringify() is a client side(browser) functionality. So you can’t do that on the server side.

Method 3

using System.Web.Helpers;

Json.Encode(obj)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x