Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

c#

asp.net

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 = "";
       }
   }
}
like image 492
Patrick Pirzer Avatar asked Feb 20 '17 11:02

Patrick Pirzer


3 Answers

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.

like image 154
user3378165 Avatar answered Oct 14 '22 16:10

user3378165


You can use something like

JsonConvert.SerializeObject(ob)

From library: Newtonsoft.Json

like image 40
danicode Avatar answered Oct 14 '22 17:10

danicode


using System.Web.Helpers;

Json.Encode(obj)
like image 38
stanley madueke Avatar answered Oct 14 '22 18:10

stanley madueke