Quantcast
Channel: Web Forms
Viewing all articles
Browse latest Browse all 23244

Send data to a javascript array and back to c# using jSON

$
0
0

Hi,

I would like to send a list of objects from c# to a javascript array .
Next, I would like to read the javascript array of objects back into a c# list of objects.

Does anyone know how this can be done?

The code behind file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;


public partial class _Default : System.Web.UI.Page
{

    List<Person> Persons;

    protected void Page_Load(object sender, EventArgs e)
    {
       Persons = new List<Person>
                        {
                          new Person{UserID= 1, UserName = "UserName1",FirstName ="FirstName1",LastName = "LastName1" },
                          new Person{UserID= 1, UserName = "UserName2",FirstName ="FirstName2",LastName = "LastName2" },
                          new Person{UserID= 1, UserName = "UserName3",FirstName ="FirstName3",LastName = "LastName3" },
                          new Person{UserID= 1, UserName = "UserName4",FirstName ="FirstName4",LastName = "LastName4" },
                          new Person{UserID= 1, UserName = "UserName5",FirstName ="FirstName5",LastName = "LastName5" },
                        };

    }

    // Send a list of objects from C# to a javascript array
    protected void btnRead_Click(object sender, EventArgs e) {

        string output = JsonConvert.SerializeObject(Persons);
        // ...
    }


    // Read a javascript array into c#
    protected void btnSend_Click(object sender, EventArgs e) {
        // ...
    }
}

The web page:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><title></title><script type="text/javascript">
        var Persons = new Array();</script></head><body><form id="form1" runat="server"><div><asp:Button ID="btnRead" runat="server" Text="Read list from server" 
            onclick="btnRead_Click" /><br /><br /><asp:Button ID="btnSend" runat="server" Text="Send array to server" 
            onclick="btnSend_Click" /></div></form></body></html>


Thanks for any feedback

Tim


Viewing all articles
Browse latest Browse all 23244

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>