【问题标题】:How to get matched records from Dictionary Model and List Model in ASP.NET Core MVC如何从 ASP.NET Core MVC 中的字典模型和列表模型中获取匹配的记录
【发布时间】:2021-02-19 19:57:33
【问题描述】:

我在一个 JSON URL 中有 8 个键/值对。我在一列中只有 4 条匹配的记录。我只需要在视图中显示 4 个匹配的记录。我创建了一个 dict 模型和其他列表模型。 ModelList Compare

根据屏幕截图,我需要 dict 中的第一个值,例如列表中的值,以便我能够在视图页面中填充 json 记录。

字典1:


     public void GetList1Void()
        {

            string strAPIUrl = "https://raw.githubusercontent.com/wedeploy-examples/supermarket-web-example/master/products.json";
            string jsonUrlProducts;
            using (WebClient client = new WebClient())
            {
                jsonUrlProducts = client.DownloadString(strAPIUrl);
            }
            Dictionary<string, object> Jsondictresults = new Dictionary<string, object>();
            var objResponseB = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(jsonUrlProducts);
            foreach (Dictionary<string, object> DictMainKV in objResponseB)
            {
                foreach (KeyValuePair<string, object> item in DictMainKV)
                {
                    Jsondictresults.Add(item.Key, item.Key);
                }
                break;
            }
            ViewBag.VBList1Void = Jsondictresults.Keys;
            ViewData["VdataList1Void"] = Jsondictresults;
        }


列表2:

public List<K360mapMaster> GetList2()
{
    List<K360mapMaster> mappingListDb = new List<K360mapMaster>();
    var query = from K360mapMaster in _context.K360mapMasters
                select K360mapMaster;
    var mappings = query.ToList();

    foreach (var mappingData in mappings)
    {
        mappingListDb.Add(new K360mapMaster()
        {
            ClientCatalog = mappingData.ClientCatalog
        });
    }
    return mappingListDb;
}

插入表格设计

Insert Table

【问题讨论】:

    标签: c# asp.net-mvc linq .net-core asp.net-core-mvc


    【解决方案1】:

    我根据你的代码做了一个简单的测试,你可以参考一下:

    var jsonmodel = new List<ApiJsonModel>
    {
        new ApiJsonModel
        {
            Title = "Brown eggs",
            Type = "dairy",
            Description = "Raw organic brown eggs in a basket",
            Filename = "0.jpg",
            Height = 600,
            Width = 400,
            Price = 28.1M,
            Rating = 4
        }
    };
    var json = JsonConvert.SerializeObject(jsonmodel);
    var SampleList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json);
            
    var SampleDBList = new List<K360mapMaster>
    {
        new K360mapMaster{ ClientCatalog = "Description"},
        new K360mapMaster{ ClientCatalog = "Price"}
    };
    
    foreach (var dicItem in SampleList)
    {
        foreach(var item in dicItem)
        {
            if (!SampleDBList.Select(s => s.ClientCatalog).ToList().Contains(item.Key))
            {
                dicItem.Remove(item.Key);
            }
        }
    }
    

    结果:

    更新:

    DataTable dt = new DataTable();
    
    var columnNames = SampleList.SelectMany(dict => dict.Keys).Distinct();
    dt.Columns.AddRange(columnNames.Select(c => new DataColumn(c)).ToArray());
    foreach (Dictionary<string, string> item in SampleList)
    {
        var row = dt.NewRow();
        foreach (var key in item.Keys)
        {
            row[key] = item[key];
        }
    
        dt.Rows.Add(row);
    }
    
    return View("Index", dt);
    

    结果:

    【讨论】:

    • 感谢您的支持。答案在调试器中工作正常。但我尝试将最终列表加载为数据表并尝试在视图中显示。它显示错误:指定的参数超出了有效值的范围。 (参数“名称”)
    • 嗨@NSiva,我从来没有在服务器端渲染过数据表,但我认为thread 可以帮助你。
    • 我一定会看的。感谢您的宝贵建议。请你再帮我一件事。我需要一个 linq 插入查询。我需要从 json 中插入 2 列,并且 4 列不是空列。我需要对非空列的列值或任何其他方式进行硬编码。该表已经由其他人设计。我现在无法更改架构。
    • @NSiva,好的,我测试过,它可以工作,看我的更新
    • 很好。数据表的好代码。显示数据表仅用于样品测试。最后的主要任务是将选定的值插入另一个表。我更新了表格设计截图。我们只有 2 个值描述和价格。什么是插入非空列的最佳方法。
    【解决方案2】:

    模型类:

     public class ApiJsonViewModel
    {
        //[JsonPropertyName("title")]
        public string Title { get; set; }
    
        //[JsonPropertyName("type")]
        public string Type { get; set; }
    
        //[JsonPropertyName("description")]
        public string Description { get; set; }
    
        //[JsonPropertyName("filename")]
        public string Filename { get; set; }
    
        //[JsonPropertyName("height")]
        public string Height { get; set; }
    
        //[JsonPropertyName("width")]
        public string Width { get; set; }
    
        //[JsonPropertyName("price")]
        public string Price { get; set; }
    
        //[JsonPropertyName("rating")]
        public string Rating { get; set; }
    }
    

    查看:

    @model System.Data.DataTable @using System.Data;
    
    <table id="example" class="table table-bordered" style="width:100%">
        <thead>
            <tr>
                @foreach (DataColumn col in Model.Columns)
                {
                    <th>@col.ColumnName</th>
                }
            </tr>
        </thead>
        <tbody>
            @foreach (DataRow row in Model.Rows)
            {
                <tr>
                    @foreach (DataColumn col in Model.Columns)
                    {
                        <td>@row[col.ColumnName]</td>
                    }
                </tr>
            }
        </tbody>
    </table>
    <form method="post">
            <table class="table table-striped table-bordered" style="width:100%">
                <tr>
                    <td align="center">
                        <button id="btnGetImportData" asp-action="GetImportData" class="btn btn-primary">Get ImportData</button>
                    </td>
                </tr>
            </table>
        </form>
    

    控制器:

     public class GetImportController : Controller
    {
        private readonly K360ECommerceSContext _context;
        public GetImportController(K360ECommerceSContext context)
        {
            _context = context;
        }
    
        public IActionResult Index()
        {           
            var resultApiJsonProp = GetApiJsonProperties();
            DataTable dt = new DataTable();
            dt = JsonConvert.DeserializeObject<DataTable>(JsonConvert.SerializeObject(resultApiJsonProp));
            return View(dt);
        }
    
        public List<ApiJsonViewModel> GetApiJsonProperties()
        {
            string strjsonUrl;
            using (WebClient client = new WebClient())
            {
                strjsonUrl = client.DownloadString("https://raw.githubusercontent.com/wedeploy-examples/supermarket-web-example/master/products.json");
            }
            List<ApiJsonViewModel> ListApiJsonProp = JsonConvert.DeserializeObject<List<ApiJsonViewModel>>(strjsonUrl);
            return ListApiJsonProp;
        }
    
      
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult GetImportData()
        {           
            var resultApiJsonProp = GetApiJsonProperties();
            var json = JsonConvert.SerializeObject(resultApiJsonProp);
            var SampleList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json);
    
            List<K360mapMaster> mappingListDb = new List<K360mapMaster>();
            var query = from K360mapMaster in _context.K360mapMasters
                        select K360mapMaster;
            var mappings = query.ToList();
            if (mappings != null)
            {
                foreach (var mappingData in mappings)
                {
                    mappingListDb.Add(new K360mapMaster()
                    {
                        ClientCatalog = mappingData.ClientCatalog
                    });
                }
            }
    
            foreach (var dicItem in SampleList)
            {
                foreach (var item in dicItem)
                {
                    if (!mappingListDb.Select(s => s.ClientCatalog).ToList().Contains(item.Key))
                    {
                        dicItem.Remove(item.Key);
                    }
                }
            }
                DataTable dataTabledt = new DataTable();
                dataTabledt = JsonConvert.DeserializeObject<DataTable>(JsonConvert.SerializeObject(SampleList));
                return View("Index",dataTabledt);
        }
    
        }
    

    【讨论】:

      猜你喜欢
      • 2017-11-15
      • 1970-01-01
      • 2015-04-29
      • 2022-11-29
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      • 1970-01-01
      相关资源
      最近更新 更多