Wednesday, April 8, 2009

Send array of objects form client to server

with this code u can send array of object form client to server in c#
u have to copy the client and server code from this post
and use this 2 dependencies:
1. JSON Code(Take js file)
2. Serialize Code(Take dll file)


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Newtonsoft.Json;
using System.Collections.Generic;

public partial class tbl1 : System.Web.UI.Page
public string tempPerson;
public string temp_arr;
public List person_arr = new List< person >();
protected void Page_Load(object sender, EventArgs e)
Person person = new Person(); = string.Empty;
person.age = 0;
string json1 = JavaScriptConvert.SerializeObject(person);
tempPerson = json1;
string json = JavaScriptConvert.SerializeObject(person_arr);
temp_arr = json;
protected void LinkButton1_Click(object sender, EventArgs e)
person_arr = JavaScriptConvert.DeserializeObject< List< person > >
public class Person
public string name;
public int age;


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Arr.aspx.cs" Inherits="tbl1" %>
<script src="json2.js" type="text/javascript"></script>
<script type="text/javascript">
var arr = <%=temp_arr%>;
var p1 = <%=tempPerson%>;
var hiDataID = '<%=hiData.ClientID%>';
function add_to_arr(name, age)
var tempP = clone(p1); = name;
tempP.age = age;
arr[arr.length] = tempP;
function add2Items()
add_to_arr("name1", 1);
add_to_arr("name2", 2);
var g = JSON.stringify(arr);
document.getElementById(hiDataID).value = g;
function clone(obj)
return JSON.parse(JSON.stringify(obj));
<form id="form1" runat="server">
<input onclick="add2Items()" type="button" value="Create Array">
<input id="hiData" type="hidden" runat="server">
<asp:linkbutton id="LinkButton1" onclick="LinkButton1_Click" runat="server">Send To Server</asp:linkbutton>

1 comment:

Anonymous said...

I always looked for this thing
Thanks man