I'm trying to do a loop in mvc5 view for particular model properties but I'm getting an error:
Additional information: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
This is the view I have:
@using App.Models
@model App.Portal.WebUI.Models.ManageViewModel
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<div class="container">
<div class="col-md-9">
<div class="col-md-12">
<div class="form-group">
@Html.LabelFor(m => m.AUser.Id)
<label>@Html.DisplayFor(m => m.AUser.Id)</label>
</div>
<div class="form-group">
@Html.LabelFor(m => m.AUser.FirstName)
@Html.TextBoxFor(m => m.AUser.FirstName)
</div>
<div class="form-group">
@Html.LabelFor(m => m.AUser.PhoneNumber)
@Html.TextBoxFor(m => m.AUser.PhoneNumber)
</div>
<div class="form-group">
</div>
</div>
<div class="col-md-12">
<div class="form-group"> </div>
<div class="form-group">
@Html.LabelFor(m => m.AUser.LastName)
@Html.TextBoxFor(m => m.AUser.LastName)
</div>
<div class="form-group">
@Html.LabelFor(m => m.AUser.Email)
@Html.TextBoxFor(m => m.AUser.Email)
</div>
</div>
</div>
<div class="col-md-3">
@foreach (AspNetRole userRole in Model.AUser.AspNetRoles)
{
@Html.CheckBox(userRole.Name, true)
@Html.Label(userRole.Name)<br />
}
</div>
</div>
The error happens in the foreach loop.
Any idea what am I doing wrong?
Code added:
ManageViewModel model = new ManageViewModel();
if (id.HasValue)
{
using (var db = new DbContext())
{
AspNetUser user = (from p in db.AspNetUsers
where p.Id == id
select p).First();
model.AUser = user;
List<AspNetRole> roles = (from r in db.AspNetRoles
select r).ToList();
model.RoleList = roles;
}
}
@foreach (AspNetRole userRole in Model.RoleList)
{
@Html.CheckBox(userRole.Name, true)
@Html.Label(userRole.Name)<br />
}
Don't use Entities connected to the DB in your ViewModel! NEVER!! It causes issues like you have just encountered. Separate layers. Read about separation of concerns separation of concerns