Reputation: 330
i created a function which gives JSON string, I wanted to bind it to Gridview. as json have array inside object so i think maybe it will required nested gridview. here is my function
List<BanquetMenuType> listMenu = new List<BanquetMenuType>();
listMenu = wsobj.GetOrdermenuTypeByOid(OrderID);
for (int i = 0; i < listMenu.Count; i++)
{
listMenu[i].data = wsobj.GetOrderMenuById(listMenu[i].OrderID, listMenu[i].MenuId);
}
var json = new JavaScriptSerializer().Serialize(listMenu);
return json;
JSON string response is:
[
{
"data": [
{
"MenuName": ""
},
{
"MenuName": "baingan"
},
{
"MenuName": "bhendi"
},
{
"MenuName": "paneer TIkka"
}
],
"OrderID": 24,
"MenuId": 1,
"MenuType": "Sabjee"
},
{
"data": [
{
"MenuName": ""
},
{
"MenuName": "cucmber chips"
}
],
"OrderID": 24,
"MenuId": 2,
"MenuType": "Salad"
}
]
I want to menu name under MenuType i dont worked on JSON before so having no idea how to bind it..
Upvotes: 1
Views: 9397
Reputation: 2202
There is no reason to convert the list object("listMenu") to JSON. It wont work as well.
Data source should be of a type that implements "IEnumerable" interface which List and Array satisfies.
List<BanquetMenuType> listMenu = new List<BanquetMenuType>();
listMenu = wsobj.GetOrdermenuTypeByOid(OrderID);
for (int i = 0; i < listMenu.Count; i++)
{
listMenu[i].data = wsobj.GetOrderMenuById(listMenu[i].OrderID, listMenu[i].MenuId);
}
outerGrid.DataSource = listMenu;
outerGrid.DataBind();
And yes, you will need to have nested grid to take care of the data property. In the RowDataBound event of the outer grid, you will need to bind the data property, to the nested grid.
Sample code:
protected void OuterGrid_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var dataItem = outerGrid.Rows[e.RowIndex].DataItem as BanquetMenuType;
GridView innerGrid = e.Row.FindControl("innerGrid") as GridView;
innerGrid.DataSource = dataItem.data;
innerGrid.DataBind();
}
}
Upvotes: 2
Reputation: 356
You can deserialize json using JsonConvert.DeserializeObject for conversion - Two ways given below
string jsonString = "Your JSON string ";
//Create a dynamic object, here you have to import Newtonsoft.Json
dynamic dynamicObject= JsonConvert.DeserializeObject(jsonString);
//Binding GridView to dynamic object
myGrid.DataSource = dynamicObject;
myGrid.DataBind();
//-----OR -----
//Using DataTable, here you have to import System.Data
DataTable dataTable= JsonConvert.DeserializeObject<DataTable>(jsonString);
//Binding GridView to dataTable object
myGridTwo.DataSource = dataTable;
myGridTwo.DataBind();
Upvotes: 2