Is it possible to pass objects (serializable classes or other ways) to a Silverlight control through asp.net server side code?
Well, it's going to involve serialization. Remember -- your Silverlight client is disconnected from the server, just like the browser is disconnected from the server.
There is a great article here on JSON serialization to and from Silverlight. Here is the summary from the article:
Let’s start with a short introduction of what JSON is. It stands for Java**S**cript Object Notation and is used as an alternative of the XML. Here is a simple example for a JSON file:
{"FirstName":"Martin","LastName":"Mihaylov"}
for a single object
And
[{"FirstName":"Martin","LastName":"Mihaylov"},{"FirstName":"Emil","LastName":"Stoychev"}]
for multiple objects.
It looks like an array. Depending on the object that is serialized it could look really complicated.
Serializing
In order to be serializable with DataContractJsonSerializer we have to set a [DataContract] attribute. The properites that will be used by the serialization must have [DataMember] attributes. Note: To use these attributes add a reference to System.Runtime.Serialization;
[DataContract]
public class Person
{
[DataMember]
public string FirstName
{
get;
set;
}
[DataMember]
public string LastName
{
get;
set;
}
}
Now we are ready to begin with the serialization. Let's create a method that takes our object as an argument and returns a string in JSON format:
public static string SerializeToJsonString(object objectToSerialize)
{
using (MemoryStream ms = new MemoryStream())
{
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(objectToSerialize.GetType());
serializer.WriteObject(ms, objectToSerialize);
ms.Position = 0;
using (StreamReader reader = new StreamReader(ms))
{
return reader.ReadToEnd();
}
}
}
Deserializing
public static T Deserialize<T>(string jsonString)
{
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
Here is what this looks like from client code:
List<Person> persons = Deserialize<List<Person>>( jsonString );