I want to get all the student have the ContractStatus == "Pending" in foreach and make a link to Edit the student
<div class="row">
@{ foreach (var studentCohort in ViewBag.CohortSubscriptionId)
{
<div class="col-md-5">
@{
var link = Html.ActionLink((string) studentCohort.ContractStatus, "Edit", "CohortSubscriptions", new { id = (object) studentCohort.ContractStatus }, new { @class ="form-control"});
var contractStatus = studentCohort.ContractStatus == "Pending" ? link : studentCohort;
}
@studentCohort.FullName (@studentCohort.contractStatus)
</div>
}
}
</div>
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Cohorts cohorts = db.Cohorts.Find(id);
if (cohorts == null)
{
return HttpNotFound();
}
var studentByCohort = db.Enrolled_Students.Where(x => x.CohortId == id).Select(x => new StudentCohortViewModel
{
CohortId = x.CohortId,
FirstName = x.FirstName,
LastName = x.LastName,
ContractStatus = x.ContractStatus
}).Distinct().ToList();
ViewBag.CohortSubscriptionId = studentByCohort;
return View(cohorts);
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''CodeboxxSchoolPortal.Models.StudentCohortViewModel' does not contain a definition for 'contractStatus''
Your choice in variable names and reassignments are hurting you here. Consequently, you're getting your types mixed and the errors you experience.
Instead of the ternary conditional (c ? a : b)
, I suggest using basic if/else which is easier to read and write.
<div class="row">
@foreach(StudentCohortViewModel studentCohort in ViewBag.CohortSubscriptionId)
{
if (studentCohort.ContractStatus == "Pending")
{
<text>
@studentCohort.FullName (@Html.ActionLink(studentCohort.ContractStatus,
"Edit",
"CohortSubscriptions",
new { id = student.ContractStatus },
new { @class = "form-control" }))
</text>
}
else
{
<text>
@studentCohort.FullName (@studentCohort.ContractStatus)
</text>
}
}
</div>
To help with identifying the correct type, instead of var studentCohort
use the more explicit StudentCohortViewModel studentCohort
.