如何在 foreach ViewBag mvc 5 中获取列表中的一项

how to get one item of the list in a foreach ViewBag mvc 5

我想让所有学生在 foreach 中都有 ContractStatus == "Pending" 并创建一个 link 来编辑学生

<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' 不包含 'contractStatus''

的定义

改变

(@studentCohort.contractStatus)

(@studentCohort.ContractStatus)

在您的 Razor 视图中。

您在变量名和重新分配方面的选择在这里伤害了您。因此,您会混淆类型并遇到错误。

我建议使用更易于读写的基本 if/else 而不是三元条件 (c ? a : b)

<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>

为了帮助识别正确的类型,请使用更明确的 StudentCohortViewModel studentCohort.

而不是 var studentCohort