I’m trying to read some data in as Json, deserialize it, and display it in my view in a DropDownList. The data looks like this:
{
"products": [
{
"body_html": "<p> ....</p>",
"created_at": "2012-09-19T11:55:44-04:00",
...
"tags": "Emotive, Flash Memory, MP3, Music",
"variants": [
{
"compare_at_price": null,
"created_at": "2012-09-19T11:55:44-04:00",
...
"inventory_quantity": 10
}
],
"images": [
{
"created_at": "2012-09-19T11:55:44-04:00",
"id": 850703190,
...
}
]
}
]
}
I’ve tried a few different things which haven’t worked. Right now I have in my controller:
var data = Newtonsoft.Json.Linq.JObject.Parse(productsJson.ToString())["products"];
SelectList productsData = JsonConvert.DeserializeObject<SelectList>(data.ToString());
ViewData["products"] = productsData;
And in the view:
@Html.DropDownList("ProductList", (SelectList)ViewData["products"])
Presently I’m getting the following error:
Cannot create and populate list type System.Web.Mvc.SelectList.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.Exception Details: System.InvalidOperationException: Cannot create and
populate list type System.Web.Mvc.SelectList.
Help is appreciated.
First, you should parse json to your product type then you may use like this: