There is an excellent tutorial on SignalR that explains how to pass .NET objects as parameters to Javascript and vice versa. In that case it passes a ChatMessage
object to and from.
However, the tutorial addresses a really simple object. I'd like to see how to deal with complex .NET objects (that have other objects as properties) in Javascript.
For instance, consider the following object:
class Master {
public List<QuarterHour> QuarterHours { get; set; }
public List<string> Books { get; set; }
public int EndDay { get; set; }
public int StartDay { get; set; }
}
class QuarterHour {
public MinuteInstance Minute {get; set;}
public int HourStart { get; set;}
}
class MinuteInstance {
public bool Registered {get; set;}
public int NumAttendees {get; set;}
}
In .NET, I can reference a value like this: master.QuarterHours[2].Minute.Registered
. My questions:
- How would I do reference
master.QuarterHours[2].Minute.Registered
in the receiver method on the Javascript end? - How would I build the
Master
object in Javascript to be sent to the .NET end?
You would want to serialize your class into a JSON object. There are many ways to accomplish this, but you can try JSON.NET to do it quick and easy.
If its not already included in your project, you can add this through Nuget with:
The code would look something like:
Once this is passed to your client-side, you can then read from your JSON object like any other. You can use the following javascript code to convert your SignalR string message to a JSON object:
You can also pass this through SignalR to the server and deserialize the JSON object using JsonConvert.DeserializeObject in order to convert it to your C# classes. Check out the documentation here for further details: http://james.newtonking.com/projects/json/help/