I have worked on reading 2 Sample Json files and try to populate in dropdownlist with values title,type,description,filename,height,width,price,rating
Json file 1==>
{"title": "Brown eggs", "type": "dairy", "description": "Raw organic brown eggs in a basket", "filename": "0.jpg", "height": 600, "width": 400, "price": 28.1, "rating": 4}
Json file 2==>
[{ "title": "Brown eggs", "type": "dairy", "description": "Raw organic brown eggs in a basket", "filename": "0.jpg", "height": 600, "width": 400, "price": 28.1, "rating": 4}]
`
` First one works fine with my code below but it's not working for the second one. It gives the error - Cannot convert type 'Newtonsoft.Json.Linq.JArray' to 'Newtonsoft.Json.Linq.JObject'
HomeController.CS Code
public IActionResult Index() { Dictionary<string, string> ProductCollectiondict = new Dictionary<string, string>(); dynamic dynObj = JsonConvert.DeserializeObject("{a:1,b:2}"); // dynamic dynObj = JsonConvert.DeserializeObject("[{a:1,b:2}]"); var jObj = (JObject)dynObj; foreach (JToken token in jObj.Children()) { if (token is JProperty) { var prop = token as JProperty; ProductCollectiondict.Add(prop.Name, (string)prop.Value); } } ViewData["selectedProductTextDict"] = ProductCollectiondict; return View(); }
Index.cshtml Code
@Html.DropDownList("ddlProductByText", new SelectList((System.Collections.IEnumerable)ViewData["selectedProductTextDict"], "Value", "Key"))
Still a long way to go in this task for various dynamic JSON URLs . Please kindly help me guide me soon
https://stackoverflow.com/questions/65880420/read-json-from-dynamic-url-and-need-to-populate-in-dot-net-core-mvc-dropdownlist January 25, 2021 at 03:18PM
没有评论:
发表评论