views:

299

answers:

2

I have the following Silverlight code:

[ScriptableType]
public partial class Page : UserControl
{
    [ScriptableMember]
    public event EventHandler<UploadChangedEventArgs> OnFileProgressChanged;

    private void FileProgressChanged_Click(object sender,RoutedEventArgs e)
    {   // test reasons only
        OnFileProgressChanged(null, new UploadChangedEventArgs()
        {
            Id = Guid.NewGuid(),
            Sent = 12345,
            Started = DateTime.Now
        });
    }
}

The event arguments have this structure:

[ScriptableType]
public class UploadChangedEventArgs : EventArgs
{
    public Guid Id { get; set; }
    public long Sent { get; set; }
    public DateTime Started { get; set; }
}

On Javascript side, I wrote the event callback (and it gets fired):

function onFileUploadProgressChanged(sender, e) {
    alert(JSON.stringify(e)); // shows "{}"
    alert(e.Sent);            // shows "12345"
}

I need to stringify that data to send it through a postback event. What's wrong?

A: 

Looking at your code, you will probably need to get the properties (Id, Sent, Started) explicitly and bulid the JSON string yourself.

function onFileUploadProgressChanged(sender, e) 
{    
    var json = "{\""Id\":\"" + e.Id + 
        "\", Sent:" + e.Sent + 
        ", \"Started\":\" + e.Started + "\"}";
}

Alternatively, you can add a property to the UploadChangedEventArgs to get the JSON (using Silverlight's JsonObject class or implement the UploadChangedEventArgs.ToString() method to return the JSON property:

using System.Json;

class UploadChangedEventArgs : EventArgs
{
   public string JSON
   {
       get
       {
            var json = new JsonObject();

            json.Add("Id", this.Id);
            json.Add("Sent", this.Sent);
            json.Add("Started", this.Started);

            return json.ToString();
       }
   }
}
Michael S. Scherotter
Hi Michael, nice ideas, but I was looking for an automatic method for property discover, just like in JSON.stringify({ Id: e.Id, Name: e.Name });Your first sample can lead to escape issues but I liked the second one.
Rubens Farias
A: 

I ended with the code below; it's similar to Michael code, but it's safer because it doesn't have to deal with character escape sequences.

function onFileListChanged(sender, e) {
  var files = [];
  for (var i = 0; i < e.Files.length; i++) {
      files[i] = {
           Id    : e.Files[i].Id, 
           Name  : e.Files[i].Name,
           Size  : e.Files[i].Size
      };
  }
  __doPostBack(
        "<%= RadGrid1.UniqueID %>", 
        "OnFileListChanged:" + JSON.stringify(files));
  }
Rubens Farias