【发布时间】:2018-08-16 16:43:57
【问题描述】:
我想要完成的是让视图显示我的所有字段。目前,我已经设置了一个 ViewModel 并将其传递给我的 View。 ViewModel如下:
NewReportViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BugTracker.Models;
namespace BugTracker.ViewModels
{
public class NewReportViewModel
{
public IEnumerable<RequestType> RequestType { get; set; }
public IEnumerable<Urgency> Urgency { get; set; }
public Report Report { get; set; }
}
}
RequestType、Urgency、Report的模型如下:
RequestType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BugTracker.Models
{
public class RequestType
{
public byte ID { get; set; }
public string RequestBC { get; set; }
}
}
Urgency.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BugTracker.Models
{
public class Urgency
{
public byte ID { get; set; }
public string UrgencyLevel { get; set; }
}
}
Report.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace BugTracker.Models
{
public class Report
{
public int ID { get; set; }
public String Name { get; set; }
public String Description { get; set; }
public RequestType RequestType { get; set; }
public Urgency Urgency { get; set; }
public String URL { get; set; }
public DateTime DateSubmitted { get; set; }
}
}
据我了解,如果我想在一个视图中获取 RequestType、Urgency 和 Report 全部内容,我需要将其作为 ViewModel 传递。
因此,我在ReportController.cs文件中做了如下操作:
public ActionResult Report()
{
var requestType = _context.RequestType.ToList();
var urgency = _context.Urgency.ToList();
var viewModel = new NewReportViewModel
{
RequestType = requestType,
Urgency = urgency
};
return View(viewModel);
}
话虽如此,我似乎无法弄清楚如何正确显示所有内容!这是我对报告的看法:
Report.cshtml
@model BugTracker.ViewModels.NewReportViewModel
@{
ViewBag.Title = "Report";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Bugs and Changes</h2>
<table class="table table-bordered table-hover">
<thread>
<tr>
<th>Issue Name</th>
<th>Request Type</th>
<th>Priority</th>
<th>Bug Description</th>
<th>URL</th>
<th>Date Submitted</th>
</tr>
</thread>
<tbody>
@foreach (var report in Model)
{
<tr>
<td>@Html.ActionLink(report.Name, "Edit", "Customers", new { id = report.ID }, null)</td>
<td>@report.RequestType.RequestBC</td>
<td>@report.Urgency.UrgencyLevel</td>
<td>@report.Description</td>
<td>@report.URL</td>
<td>@report.DateSubmitted.ToShortDateString()</td>
</tr>
}
</tbody>
</table>
每当我尝试运行它时,它都会抱怨IEnumerable。根据我的研究,看起来@foreach 行需要所有数据为IEnumerable。但是,显然 Report.cs 模型不是 IEnumerable(我认为我也做不到)。
但是,我的 Urgency.cs 和 RequestType.cs 模型需要为 IEnumerable,因为我将它们用作创建新表单的视图中的下拉选项。这引出了我的问题:
如何查看包含 IEnumerable 字段和非 IEnumerable 字段的 ViewModel 并让它显示所有字段?我需要改变什么?
【问题讨论】:
-
您没有在视图模型中通过“报告”
标签: asp.net asp.net-mvc asp.net-mvc-4