我正在使用ASP.NET MVC創建一個網站,我想顯示一個對象的列表,我從數據庫中檢索到另一個列表,被收回。ASP .NET MVC-不能在視圖中嵌套foreach循環來顯示列表
這裏是我的模型:
public class JournalViewModel
{
public JournalViewModel()
{
Issues = new List<Issue>();
}
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required, DataType(DataType.MultilineText)]
public string Description { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
public byte[] Content { get; set; }
[Required, ValidateFile]
public HttpPostedFileBase File { get; set; }
public int UserId { get; set; }
[Required, DataType(DataType.MultilineText)]
public string IssueDescription { get; set; }
[Required]
public string IssueTitle { get; set; }
[Required]
public int IssueNumber { get; set; }
public int IssueId { get; set; }
public ICollection<Issue> Issues { get; set; }
}
我的控制器:
public ActionResult Index()
{
var userId = (int)_membershipService.GetUser().ProviderUserKey;
List<Journal> allJournals = _journalRepository.GetAllJournals(userId);
var journals = Mapper.Map<List<Journal>, List<JournalViewModel>>(allJournals);
return View(journals);
}
而我的觀點:
@model List<Journals.Model.JournalViewModel>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@section Style
{
<style type="text/css">
.table {
table-layout: fixed;
}
.table td {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
}
<h2>Publisher - List of Journals</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
@if (Model.Count == 0)
{
<div> Click @Html.ActionLink("here", "Create") to publish your first Journal.</div>
}
else
{
<table class="table table-condensed table-striped">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>File</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.ActionLink(item.FileName, "GetFile", new { Id = item.Id }, new { target = "_blank" })
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
@foreach (var issue in item.Issues)
{
<tr>
<td>
@Html.DisplayFor(i => issue.IssueTitle)
</td>
</tr>
}
}
</tbody>
</table>
}
該視圖中使用,直到我說這個代碼工作正常:
@foreach (var issue in item.Issues)
{
<tr>
<td>
@Html.DisplayFor(i => issue.IssueTitle)
</td>
</tr>
}
現在它已停止工作。我做錯了什麼?
此外,有沒有辦法從這個視圖檢索錯誤消息?
「停止工作」是什麼意思?此外,'JournalViewModel'具有'IssueTitle,IssueNumber,IssueId'屬性,還有'Issue'列表;爲什麼這三個屬性看起來應該是'Issue'的屬性? –
你的'Issue'類是什麼樣的? 'IssueTitle'看起來像是'JournalViewModel'的屬性,而不是'Issue' –
嗨,是@PaulAbbott這些屬性應該是Issue類的一部分,但是我在那裏添加了它們,以便我可以做一些測試。他們將被刪除。 – Felipe