编辑我的视图使用雇主模型。Employer和JobPosting之间存在1:M关系。我将更多地分享关于上下文的观点。
上下文:在我的申请中,我想向雇主显示申请JobPosting的申请人人数。我目前编写的代码没有返回任何值。它没有抛出任何错误,但也不起作用。我很确定问题出在我的控制器上,但我也会提供模型和视图。
控制器:
public ActionResult AppCount()
{
foreach (var app in db.JobPostings.ToList())
{
int id = app.JobPostingID;
int count= db.Applications.Where(a => a.JobPostingID == id).Count();
app.AppCount = count;
ViewBag.AppCount = count;
}
return View();
}
视图:
@model InTurn_Model.Employer
.
.
.
<h2>My Job Postings</h2>
<p>
@Html.ActionLink("Create New", "Create", "JobPostings", null, null)
</p>
<div id="employeeContainer"></div>
<table class="table table-striped">
<tr>
<th>Position</th>
<th>Job Type</th>
<th>Number of Applicatiosn</th>
<th></th>
</tr>
@foreach (var item in Model.JobPostings)
{
if (item.EmployerID == Model.EmployerID)
{
<tr>
<td>
@Html.DisplayFor(model => item.Position)
</td>
<td>
@Html.DisplayFor(model => item.JobType)
</td>
<td>@ViewBag.AppCount</td>
<td>@Html.ActionLink("Details", "Details", "JobPostings", new { id = item.JobPostingID }, null) </td>
</tr>
}
}
</table>
型号:
[MetadataType(typeof(JobPostingMetaData))]
public partial class JobPosting
{
public int AppCount { get; set; }
private sealed class JobPostingMetaData
{
[Display(Name = "Job Posting ID")]
public int JobPostingID { get; set; }
[Display(Name = "Employer ID")]
public int EmployerID { get; set; }
[Display(Name = "Description")]
public string Desc { get; set; }
[Display(Name = "Job Type")]
public JobType JobType { get; set; }
[Display(Name = "Employment Type")]
public TimeType TimeType { get; set; }
[DataType(DataType.Currency)]
public decimal Wage { get; set; }
}
}
我看到了两个问题。
首先,您没有将Model
从控制器传递到视图。但是,您正在通过Model.JobPostings
进行迭代。它是空的。
其次,在循环中指定ViewBag.AppCount
。因此,除最后一个值外,所有值都将丢失。但是,如果你解决了第一个问题(使用Model
而不是ViewBag
(,第二个问题可能会自行消失。
您需要使用@model:在视图中指定模型
@model YourNameSpace.JobPosting
然后将该模型返回到视图:
public ActionResult AppCount()
{
foreach (var app in db.JobPostings.ToList())
{
int id = app.JobPostingID;
int count= db.Applications.Where(a => a.JobPostingID == id).Count();
app.AppCount = count;
ViewBag.AppCount = count;
}
return View(app);
}
这将使模型中的值可用于视图。不需要使用ViewBag,因为AppCount是模型的一部分。
我想得太多了。我只需要从JobPosting模型中设置它,然后剩下的就可以了,我根本不需要遍历Controller。
public int AppCount => Applications.Count;