Can I use a C# codebehind to return my JSON?

Can I use a C# codebehind to return my JSON?

meghnasapremeghnasapre Posts: 5Questions: 0Answers: 0
edited February 2013 in General
Can I use a C# code behind to return my JSON?
I tried and it threw an error, I might be doing something wrong.

I am currently writing my JSON to a text file through CS by and it works great.
However, my columns are dynamic depending upon user preferences, so the text file will keep getting regenerated, my concern is that it might get locked if people try to access the page at the same time.

I need quite a bit of back-end processing which I already have in C#, trying to avoid duplicating everything in PHP.

Thanks,
Meghna

Replies

  • allanallan Posts: 63,522Questions: 1Answers: 10,473 Site admin
    > Can I use a C# code behind to return my JSON?

    Yes - as long as you can create valid JSON, then you can use any language.

    Allan
  • meghnasapremeghnasapre Posts: 5Questions: 0Answers: 0
    Thanks -I'll try it out again.
  • gcuttsgcutts Posts: 2Questions: 0Answers: 0
    edited February 2013
    not that you can't figure it out, but in case this helps you understand things quicker ..
    Let's say you want the following in JSON:
    {
    "FirstName": "John",
    "LastName": "Doe",
    "isAlive": true
    }

    you would do this in C# as follows:
    class CPerson
    {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Boolean isAlive { get; set; }
    [ScriptIgnore]
    public int SomePropDontSerialize { get; set; }

    public CPerson(string pFName, string pLName, Boolean pIsAlive, int pSomePropDontSerialize)
    {
    this.FirstName = pFName;
    this.LastName = pLName;
    this.isAlive = pIsAlive;
    this.SomePropDontSerialize = pSomePropDontSerialize;
    }
    }

    CPerson _person = new CPerson("John", "Doe", true, 666);

    string _JSON = new JavaScriptSerializer().Serialize(_person);

    I hope this helps speed things up a bit.

    NOTE: if you need arrays in JSON you can use Lists in .NET and they serialize to arrays.
  • meghnasapremeghnasapre Posts: 5Questions: 0Answers: 0
    Thank you gcutts!

    I got it working, although I do need a small clarifcation.

    I have a page Main.aspx where I initialize and draw my table.

    I have a GetData.aspx, and in GetData.aspx.cs, I do my processing and return the JSON.

    To get the JSON in my Main.aspx, I am currently doing this in my GetData.aspx.

    <%
    var value = GetData();
    Response.Write(value); %>

    My question is, is there a nicer way to do this?
    It takes about 4 sec to load ~900 rows (which is not good enough for some customers :-) )

    Thanks!
    Meghna
This discussion has been closed.