Al.
Al.

Reputation: 875

Bind JSON object to asp.net gridview control using javascript

My jquery ajax called my codebehing static WebMethod and I used System.Web.Script.Serialization.JavaScriptSerializer to get JSON object and the output is something like this.

[{"ProductId":"9","Category":"TV","Products":"Discovery","Price":15.97},{"ProductId":"25","Category":"TV","Products":"HBO","Price":15.97}]

I have GridView(asp.net control) which has ProductId, Category, Products, Price columns. I should bind this json object to the gridview using the JavaScript.

I dont know even how to apply for loop on the above Json string. Please show some light on this.

Upvotes: 0

Views: 7021

Answers (3)

Shyju
Shyju

Reputation: 218702

You can loop thru your JSON data like this

var data=[{"ProductId":"9","Category":"TV","Products":"Discovery","Price":15.97},
          {"ProductId":"25","Category":"TV","Products":"HBO","Price":15.97}];

$.each(data,function(index,item){
    alert(item.ProductId);
    alert(item.Category);
}); 

To replace the Grid, You can build the HTML markup for a table and inject that to the DOM.

 var itemRow="<table>";  
 $.each(data,function(index,item){
    itemRow+="<tr><td>"+item.ProductId+"</td><td>"+item.Category+"</td></tr>";
 });        
 itemRow+="</table>";  

 $("#divItems").html(itemRow);

Working sample http://jsfiddle.net/qS7uD/6/

But you will not get the ASP.NET Grid Events after this as it is pure HTML markup for the display

Upvotes: 1

John Need
John Need

Reputation: 60

To Deserialize your JSON you should create a class with the same properties and use the JavascriptSerilzier like this.

public class Product
{
  public int ProductId{get;set;}
  public string Category{get;set;} 
  public string Products{get;set;} 
  public decimal Price{get;set;}
} 


myProducts List<Product> = new JavaScriptSerializer().Deserialize<List<Project>>(myJson);

You can then loop through your product list using a simple for-each loop. You can aslo bind your control using the List as a data source.

Upvotes: 0

ryudice
ryudice

Reputation: 37366

You cant do that with the default asp.net grid, checkout jQGrid for json-based grid

Upvotes: 0

Related Questions