2

Is it possible to pass objects (serializable classes or other ways) to a Silverlight control through asp.net server side code?

1 Answer 1

3

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 JavaScript 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 );
Sign up to request clarification or add additional context in comments.

1 Comment

How do I pass that to the silverlight control? Do I just register a script block on the page, then look for a javascript variable somehow in the silverlight control?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.