Sending complex typed data from web service to SilverLight client - Part II
Sending complex typed data from web service to SilverLight client - Part II
On my previous post I've explained the first steps of creating the service and methods on the server side, and the client
corresponding objects in the Silverlight project. Here I'll go further on the JavaScript mediator side.
After making the Web method for getting the employee, we have to call it from out JavaScript mediator, convert the objects received from the server to the SilverLight corresponding ones, and serialize the objects for our SilverLight component.
Step 3 - Create the JavaScript mediator:
Here is the code for the service call (very simple one but nevertheless...)
function loadEmployees()
{
Billing.GetAllEmployees(onGettingAllEmployeesSuccess, onError);
}
Step 4 - Write the Databind Method on the SilverLight control code
In order to operate methods of your Silverlight control from
JavaScript code, you have to decorate your control class with
ScriptableType attribute and your methodswhich you want to access
with ScriptableMember attribute
[ScriptableType]
public partial class Page
{
.
.
.
//Method to access from JavaScript
[ScriptableMember]
public void BindListBox(string employeesString)
{
MemoryStream memStr = null;
try
{
//Deserialize the data received from the JavaScript mediator
var jSer = new DataContractJsonSerializer(typeof(Employee[]));
memStr = new MemoryStream(Encoding.Unicode.GetBytes(employeesString));
var employees = jSer.ReadObject(memStr) as Employee[];
//Bind the deserialized object with a control (Listbox in that case)
Employee.ItemsSource = employees;
Employee.Width = GetMaxWidth();
}
catch (Exception ex)
{
//This is for debuging, you can operate JavaScript methods of the page
// as an HtmlPage public methods
var message = ex.Message;
HtmlPage.Window.Alert(message);
}
finally
{
//Close the memory stream to release resources
if (memStr != null)
{
memStr.Close();
}
}
}
}
On my next and last post I'll go into the JavaScrip mediator
and sum everything up.