Push a copy of an object to client
By Anatoly Mironov
To reduce postbacks and database calls, a copy of the current object(s) can be pushed down to the client in JSON format. Say a webpart renders information about a person, another webpart shows related information which is retrieved dynamically (like web services). Instead of getting the current person from the database in the second webpart again, we can reuse the same person object from the first webpart. To do so we must provide a DataContract for the Person class:
\[DataContract\]
public class Person
{
\[DataMember\]
public string Firstname { get; set; }
\[DataMember\]
public string Lastname { get; set; }
\[DataMember\]
public string PhoneMobile { get; set; }
...
```Then we can serialize the current object using [DataContractJsonSerializer](http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx):
private void RegisterPersonOnClient(Person person) { var serializer = new System.Runtime.Serialization.Json .DataContractJsonSerializer(person.GetType()); var ms = new MemoryStream(); serializer.WriteObject(ms, person); var json = Encoding.UTF8.GetString(ms.ToArray()); var script = “var personOnClient = " + json + “;\n”; Page.ClientScript .RegisterStartupScript(GetType(), “uniqueScriptKey”, script, true); }
function openRemoteModalDialog() { if (typeof (personOnClient) !== undefined) { var p = { firstname: personOnClient.Firstname, lastname: personOnClient.Lastname, email: personOnClient.Email, mobile: personOnClient.PhoneMobile }; var q = “?” + $.param(p); openModalDialog(remoteUrl + q); } }