使用动作结果渲染MVC中的局部视图,处理ObjectContext

时间:2016-06-27 18:57:07

标签: c# asp.net-mvc linq partial-views dispose

我正在尝试使用以下视图填充部分视图:

@{Html.RenderAction("AppointmentsView", "Appointment", new { id = Model.PatientId });}

我的行动结果如下:

    public ActionResult AppointmentsView(int id)
    {
        using (var context = new WaysToWellnessDB())
        {
            IEnumerable<AppointmentDiary> appointments = context.AppointmentDiaries.Where(a => a.PatientId == id).ToList();

            var accountUsers = context.AccountUsers.Select(rr => new SelectListItem { Value = rr.AccountUserId.ToString(), Text = rr.FirstName + " " + rr.LastName }).ToList();
            ViewBag.AccountUsers = accountUsers;

            var location = context.Locations.Select(rr => new SelectListItem { Value = rr.LocationId.ToString(), Text = rr.LocationDesc }).ToList();
            ViewBag.Location = location;

            return PartialView("/Views/Patient/Appointment/_ViewAppointments.cshtml", appointments);
        }
    }

我的部分观点如下:

@foreach (var item in Model)
{
    <tr>
        <td>@Html.DisplayFor(x => item.DateTimeScheduled)</td>
        <td>@Html.DisplayFor(x => item.AppointmentLength)</td>
        <td>@Html.DisplayFor(x => item.AccountUser.FirstName) @Html.DisplayFor(x => item.AccountUser.LastName)</td>
        <td>@Html.DisplayFor(x => item.Location.LocationDesc)</td>
        <td>@Html.DropDownListFor(x => item.AttendedStatusId, (IEnumerable<SelectListItem>)ViewBag.AppointmentStatus, null, htmlAttributes: new { @class = "form-control", @id = "appointmentStatusId", onchange = "alert(this.options[this.selectedIndex].value);" })</td>
    </tr>
}

这是倒下的,说如下:

  

ObjectContext实例已被释放,不能再用于需要连接的操作。

我尝试在我的linq查询中使用.Inlcude,但是这没有用..有什么想法没有用吗?

2 个答案:

答案 0 :(得分:1)

Alexander Derck发布的答案是我需要在顶部的using语句中包含System.Data.Entity,然后以下工作。

    public ActionResult AppointmentsView(int id)
    {
        using (var context = new WaysToWellnessDB())
        {
            IEnumerable<AppointmentDiary> appointments = context.AppointmentDiaries.Include(p => p.AccountUser).Include(p => p.AttendedStatus).Include(p => p.Location).Where(a => a.PatientId == id).ToList();

            return PartialView("/Views/Patient/Appointment/_ViewAppointments.cshtml", appointments);
        }
    }

答案 1 :(得分:0)

您已经实现了“使用”块,该块在完成执行“使用”块后处理该对象。因此,当您尝试访问虚拟属性“item.AccountUser.FirstName”时,由于上下文对象已经处理掉,它将抛出“已放置ObjectContext实例”错误。 由Alexander Derck发布,使用include将解决此问题,因为在上下文对象仍处于活动状态时,您将提前包含所有必需的虚拟属性。 希望这能解释。