Silverlight JSON POST

By Peter Bromberg

Create a SilverLight application. Create two buttons on SilverLight markup. One for getting the records from the service and other for Insert into the service. Right click on SilverLight application and add the class Test. Because in REST services DataContract are not exposed to the client.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SilverLightRestTesting
public class Test
public int Marks { get; set; }
public String Name { get; set; }

Let us suppose button name is Insert for Insert into Static list of service. Write below code on click event of Insert button.
private void Insert_Click(object sender, RoutedEventArgs e)
Test t1 = new Test() { Name = "Civics", Marks = 100 };
DataContractJsonSerializer jsondata = new DataContractJsonSerializer(typeof(Test));
MemoryStream mem = new MemoryStream();
string josnserdata = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
WebClient cnt = new WebClient();
cnt.UploadStringCompleted += new UploadStringCompletedEventHandler(cnt_UploadStringCompleted);
cnt.Headers["Content-type"] = "application/json";
cnt.Encoding = Encoding.UTF8;
cnt.UploadStringAsync(new Uri(uri), "POST", josnserdata);
void cnt_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
var x = e;
4. To get all the records in form of JSON from REST service , let us suppose button name is Display. Then write below code on click event of Display button.
private void display_Click(object sender, RoutedEventArgs e)
WebClient cnt = new WebClient();
cnt.DownloadStringCompleted += new DownloadStringCompletedEventHandler(cnt_DownloadStringCompleted);
cnt.DownloadStringAsync(new Uri(uri));
void cnt_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)

string str = e.Result;
JsonArray json;
if (JsonArray.Parse(str) as JsonArray == null)
json = new JsonArray { JsonObject.Parse(str) as JsonObject };
json = JsonArray.Parse(str) as JsonArray;
var q = from t in json
select new Test
Marks = (int)t["Marks"],
Name = (String)t["Name"]
List<Test> tr = q.ToList() as List<Test>;

Silverlight JSON POST  (3150 Views)