1
我对MVC,JSON,Razor和.Net非常陌生 - 对我来说很容易。在MVC和Razor中访问嵌套的JSON元素
我一直在努力通过CosmosDB demo from Microsoft没有问题。
然后我开始使用代码作为基础将嵌套的JSON元素检索到HTML表格中。我已经成功地为第一层嵌套元素做了这些工作,但一直在与第二层级挣扎。
这是一个示例JSON文档。
{
"title": "War Diary for 2nd Battalion Scots Guards September 1943",
"date": "September 1943",
"unit": "2nd Battalion Scots Guards",
"brigade": "201 Guards Brigade",
"division": "56 Infantry Division",
"entries": [
{
"day": "1st",
"location": "Tripoli",
"time": "",
"text": [
{
"p": "The L.S.T. party march to the Race Course prior to embarkation...."
}
]
},
{
"day": "2nd",
"location": "",
"time": "",
"text": [
{
"p": "A two hours march brings the L.S.T. party to the quay..."}
]
},
{
"day": "3rd",
"location": "",
"time": "",
"text": [
{
"p": "The \"fighting four hundred\"; or the two L.C.I's parties march..." },
"p": "The L.C.I. parties embark. Last minute-farewells. Convoy sails after dark..."}
]
}
}
]
}
这是模型:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
namespace todo.Models
{
public class WarDiary
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "title")]
public string Title { get; set; }
[JsonProperty(PropertyName = "date")]
public string Date { get; set; }
[JsonProperty(PropertyName = "unit")]
public string Unit { get; set; }
[JsonProperty(PropertyName = "brigade")]
public string Brigade { get; set; }
[JsonProperty(PropertyName = "division")]
public string Division { get; set; }
[JsonProperty(PropertyName = "entries")]
public Entry [] Entries { get; set; }
}
public class Entry
{
[JsonProperty(PropertyName = "text")]
public Details[] Text { get; set; }
[JsonProperty(PropertyName = "day")]
public string Day { get; set; }
[JsonProperty(PropertyName = "time")]
public string Time { get; set; }
[JsonProperty(PropertyName = "location")]
public string Location { get; set; }
}
public class Details
{
[JsonProperty(PropertyName = "p")]
public string P { get; set; }
}
}
的观点是:
@model todo.Models.WarDiary
@{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Details</h2>
<div>
<h4>WarDiary</h4>
<hr />
<table class="table">
<tr>
<th>
Location
</th>
<th>
Day
</th>
<th>
Time
</th>
<th>
Summary
</th>
</tr>
@foreach (var entry in Model.Entries)
{
<tr>
<td>
@entry.Location
</td>
<td>
@entry.Day
</td>
<td>
@entry.Time
</td>
<td>
@foreach (var p in Model.Entries.Text)
{
<p>
@p.P
</p>
}
</td>
</tr>
}
</table>
我可以成功地检索的元素在条目(日期,时间,地点),但一旦我尝试访问详细信息(嵌套文本)我似乎无法引用它。
的问题是这一行:
@foreach (var p in Model.Entries.Text)
为此,我得到的错误
“进入[]”不包含“文本”,并没有扩展方法“文本”的定义接受类型'Entry []'的第一个参数可以找到(你是否缺少使用指令或程序集引用?)。
我试过在Entry中嵌套类的细节,但似乎有同样的问题。我假设它与模型的定义有关。
任何建议感激地收到!
完美。谢谢! – GPT