編輯我的觀點是使用雇主模型。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; }
}
}
uj5u.com熱心網友回復:
我看到了兩個問題。
首先,您不是Model從控制器傳遞到視圖。但是,您正在迭代Model.JobPostings. 它是空的。
ViewBag.AppCount其次,您在回圈中分配。因此,除了最后一個值之外,所有值都將丟失。但是,如果您解決了第一個問題(使用Model而不是ViewBag) - 第二個問題可能會自行消失。
uj5u.com熱心網友回復:
您需要在視圖中使用@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 是模型的一部分。
uj5u.com熱心網友回復:
這個我想多了。我只需要從 JobPosting 模型進行設定,然后其余的作業就可以了,我根本不需要遍歷 Controller。
public int AppCount => Applications.Count;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/459889.html
標籤:C# asp.net-mvc 视觉工作室
下一篇:如何在下面做一個動態href?
