Friday, September 24, 2010

Call webservice method at server side which return data in json formate

In my previous post i have done with how to access the webservice method at client side using jQuery and how to handle the json data which is return by
webservice method.In this post i describe how we can handle the json data the webservice method at client using jQuery.

-> Take one .asmx file in your peoject for creating webservice.
-> For that i can used Northwind database and in that i take product table ( Linq To Sql Classes => .dbml file).
-> I used JavaScriptSerializer class for the convert data into json formate

public string Getjsondata()
{
string jsonstring = "";

NorthwindDataContext ObjDataContext = new NorthwindDataContext();

var product = from p in ObjDataContext.Products
select new { p.ProductID, p.ProductName };

JavaScriptSerializer js = new JavaScriptSerializer();
jsonstring = js.Serialize(product).ToString();

return jsonstring;
}


-> Now add created webservice in your project using "Add Web References".You can see in the image i have add webservice and give the name "jsonproduct".

-> For getting json data at server side we can create one "JsonProduct" class

class JsonProduct
{
public string productid { get; set; }
public string productname { get; set; }

}


-> After this you can access the webservice method in .cs file using webservice class in my case i have "getproduct" class and also i am adding one
dropdownlist in .aspx page

// Web Service Class and create the the object of that class
getproduct ObjProduct = new getproduct();

// Using created object i can call the webservice method and take the json data into string variable
string jsonstring = ObjProduct.HelloWorld();

// After that i can used JavaScriptSerializer class for Deserialize json string and store the data into IList
IList<JsonProduct> persons = new JavaScriptSerializer().Deserialize<IList<JsonProduct>>(jsonstring);

// Bind IList object to dropdownlist datasource
ddlProduct.DataSource = persons;
ddlProduct.DataTextField = "productname";
ddlProduct.DataValueField = "productid";
ddlProduct.DataBind();

No comments: