c# - 如何使用 .NET Core MVC 在 View 中解析和显示 JSON 数据?
问题描述
如何在下面显示 JSON 响应(从 REST API 接收)并以过滤的方式将其显示在我的视图 (MVC) 中?
作为一种解决方案,我尝试为其创建模型,请参见下面的结果,但问题是我无法过滤视图显示中的字段(例如,我只想显示“站点名称”的搜索结果页面和忽略其他的)。此外,我认为最好有一个 Dictionary<string, string> 而不是带有键和值的列表,但是 JSON 反序列化器在这方面限制了我,因为我使用以下行将 JSON 转换为模型:
Models.Root convertedToModel = JsonConvert.DeserializeObject<Models.Root>(jsonData);
我也尝试使用 ViewData,但不断收到 NullReferenceException。有关以过滤方式在视图中显示 JSON 数据的更好方法的任何建议?
{
"Results": {
"Rows": [{
"Cells": [{
"Key": "Title",
"Value": "Some Document - 1234 ABC",
"ValueType": "Edm.String"
},
{
"Key": "Path",
"Value": "https: //contoso.sharepoint.com/sites/shipments/Shared documents/Some Document - 1234 ABC.pdf",
"ValueType": "Edm.String"
},
{
"Key": "SiteName",
"Value": "https: //contoso.sharepoint.com/sites/shipments",
"ValueType": "Edm.String"
}
]
},
{
"Cells": [{
"Key": "Title",
"Value": "Some Document - 9432 XYZ",
"ValueType": "Edm.String"
},
{
"Key": "Path",
"Value": "https: //contoso.sharepoint.com/sites/shipments/Shared documents/Some Document - 9432 XYZ.pdf",
"ValueType": "Edm.String"
},
{
"Key": "SiteName",
"Value": "https: //contoso.sharepoint.com/sites/shipments",
"ValueType": "Edm.String"
}
]
}
]
},
"TotalResult": 2
}
基于 JSON 数据创建模型:
public class Cell
{
public string Key { get; set; }
public string Value { get; set; }
public string ValueType { get; set; }
}
public class Row
{
public List<Cell> Cells { get; set; }
}
public class Results
{
public List<Row> Rows { get; set; }
}
public class Root
{
public Results Results { get; set; }
public int TotalResult { get; set; }
}
看法:
<table class="table">
@foreach (var item in Model.ToList())
{
<tr>
@foreach (var cellItem in item.Cells)
{
<th>@cellItem.Key</th>
}
</tr>
<tr>
@foreach (var cellItem in item.Cells)
{
<td>@cellItem.Value</td>
}
</tr>
}
</table>
解决方案
在我看来,如果单元格的密钥格式始终相同,我建议您可以在控制器内部进行转换,然后将新创建的视图模型传递给 MVC 视图。
例如,您可以传递一个新模型列表。
结果妆容:
public class Result
{
public String Path { get; set; }
public String Title { get; set; }
public String SiteName { get; set; }
//if it contains new cell you could add some new property
}
然后您可以编写一个转换方法来使用 foreach 或者将此 Root 转换为List<Result>
.
推荐阅读
- javascript - 如何在 Mediawiki 中启用网站的移动视图?
- android - Play 控制台中的任何 Android 应用程序是否出现在 Google Api 控制台中
- amazon-web-services - 由于资源已存在,Cloudformation 模板失败
- python - 如何更改调用哪个变量?(特别是对象)
- java - Apache箭头可以支持无限级嵌套结构吗?
- neo4j - 将 URL 查询转换为节点
- jquery - iframe 上的 jQuery 和 postMessage
- excel - 公式 excel 按代码显示名字或姓氏
- arrays - 在ruby中将字符串转换为数组?
- java - 无法在 java poi 中读取 excel 文件(.xls)