【问题标题】:Populate Dropdownlist in Dotnet Core MVC - Parse from dynamic JSON Product URL在 Dotnet Core MVC 中填充下拉列表 - 从动态 JSON 产品 URL 解析
【发布时间】:2021-01-26 07:57:03
【问题描述】:

示例 JSON 文件:

{ "products" : [{ "Name": "Cheese", "Price" : 2.50, "Location": "Refrigerated foods"},{ "Name": "Crisps", "Price" : 3, "Location": "the Snack isle"},  { "Name": "Pizza", "Price" : 4, "Location": "Refrigerated foods"},  { "Name": "Chocolate", "Price" : 1.50, "Location": "the Snack isle"},  { "Name": "Self-raising flour", "Price" : 1.50, "Location": "Home baking"},  { "Name": "Ground almonds", "Price" : 3, "Location": "Home baking"}]}

Controller.cs 代码

 public IActionResult Index()
    {
        var webClient = new WebClient();
        //var jsonUrlProducts = webClient.DownloadString(@"https://raw.githubusercontent.com/mdn/fetch-examples/master/fetch-json/products.json");
        var jsonUrlProducts = webClient.DownloadString(@"C:\Users\NatarajanS\source\repos\KC_EC_WebSite_1\KC_EC_WebSite_1\wwwroot\lib\JSON\Json_F3.json");

        var dictProducts = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonUrlProducts);

        ViewData["selectedProductTextDict"] = dictProducts;             
     
        return View();
    }

Index.cshtml 代码:

 @Html.DropDownList("ddlProductByText",
       new SelectList((System.Collections.IEnumerable)ViewData["selectedProductTextDict"], "Value", "Key"))

{ "products" : [{ "Name": "Cheese", "Price" : 2.50, "Location": "Refrigerated foods"}] }

我需要使用对象键名称填充我的下拉列表。来自上述 JSON 文件的示例 .. 名称、价格、位置

但上面的代码只填充了我的根对象名称products

【问题讨论】:

    标签: c# json asp.net-core model-view-controller


    【解决方案1】:

    Dropdownlist values 正如Atabai所说,你需要创建一个模型来映射json。对于你的json,模型设计应该是:

    public class Test
    {
        public List<Product> products { get; set; }
    }
    
    public class Product
    {
        public string Name { get; set; }
        public float Price { get; set; }
        public string Location { get; set; }
    }
    

    控制器:

    [HttpGet]
    public ActionResult Index()
    {
        //....
        var dictProducts = JsonConvert.DeserializeObject<Test>(jsonUrlProducts);
    
        ViewData["selectedProductTextDict"] = dictProducts.products;
        return View();
    }
    

    查看(例如填充姓名列表):

    @Html.DropDownList("ddlProductByText",
          new SelectList((System.Collections.IEnumerable)ViewData["selectedProductTextDict"], "Name", "Name"))
    

    结果:

    更新:

    如果您只想显示名称、价格、位置,请检查以下代码:

    [HttpGet]
    public ActionResult Index()
    {
           //...
            var dictProducts = JsonConvert.DeserializeObject<Dictionary<string,object>>(jsonUrlProducts);
            var data =(JArray)dictProducts["products"];
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (JObject obj in data.Children())
            {
                foreach (JProperty prop in obj.Children())
                {
                    string key = prop.Name.ToString();
                    string value = prop.Value.ToString();
                    dic.Add(key, value);
                }
                break;
            }          
            ViewData["selectedProductTextDict"] = dic;
            return View();
    }
    

    查看:

    @Html.DropDownList("ddlProductByText",
          new SelectList((System.Collections.IEnumerable)ViewData["selectedProductTextDict"], "Value", "Key"))
    

    结果:

    【讨论】:

    • 非常感谢您的快速回复。我的任务是我只需要使用示例产品 json 中的键名 ** 名称、价格、位置 ** 填充下拉列表
    • 嗨@NSiva,请查看我更新的答案。如果我的回答帮助您解决了您的问题,请您接受作为答案吗?如果没有,请您跟进让我知道吗?参考:@ 987654324@.Thanks.
    • key 'products' 被以下文件中的 key 'CO' 替换。当我用 CO 替换产品时它工作正常。但是这样的硬编码不好。有没有办法从字典中获取动态键。 {"CO": [{"product-name": "MEN'S BETTER THAN NAKED™ JACKET","product-image-url": "images.thenorthface.com/is/image/TheNorthFace/236x204_CLR/…", "header-top-right-text": "Shop All" ,"header-top-left-text": "男士","product-url": "thenorthface.com/catalog/sc-gear/…"}]}
    • 非常感谢@Rena。你的代码工作正常。非常感谢您的宝贵时间。
    • key 'products' 被以下文件中的 key 'CO' 替换。当我用 CO 替换产品时它工作正常。但是像这样硬编码并不好。有没有办法从字典中获取动态键。 {"CO": [{"product-name": "MEN'S BETTER THAN NAKED™ JACKET","product-image-url": images.thenorthface.com/is/image/TheNorthFace/236x204_CLR/…", "header-top-right-text": "Shop All", "header-top-left-text": "男士", "product-url": "thenorthface.com/catalog/sc-gear/…" }] }
    【解决方案2】:

    我认为你必须创建类对象并使用它,就像下面的代码:

        public class Product    {
            public string Name { get; set; } 
            public double Price { get; set; } 
            public string Location { get; set; } 
        }
    
    

    它可以帮助您访问所有道具。

    【讨论】:

    • 感谢您的快速回复。我的任务是我只需要使用示例产品 json 中的键名 ** 名称、价格、位置 ** 填充下拉列表
    猜你喜欢
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多