我有這樣的觀點:的ObjectContext的實例已被設置,並且不再能夠用於需要連接的操作
@model MatchGaming.Models.ProfileQuery
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm("Results", "Profiles")) {
@Html.ValidationSummary(true)
<fieldset>
<legend>ProfileQuery</legend>
@Html.EditorFor(model=>model.SearchString)
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
我有這樣的控制器爲HttpPost:
[HttpPost]
public ActionResult Results(ProfileQuery profileQuery)
{
Debug.Write(profileQuery.SearchString);
using(var db = new MatchGamingEntities())
{
var SearchUserName = db.Users.SingleOrDefault(a=> a.UserName.Contains(profileQuery.SearchString));
var Users = from m in db.Users
join m2 in db.MyProfiles on m.UserId equals m2.UserId
where m.UserName == SearchUserName.UserName
select new UserViewModel
{
UserName = m.UserName,
LastActivityDate = m.LastActivityDate,
Address = m2.Address,
City = m2.City,
State = m2.State,
Zip = m2.Zip
};
return View(Users.AsEnumerable());
}
}
這裏是該信息查看結果:
@model IEnumerable<MatchGaming.Models.UserViewModel>
@{
ViewBag.Title = "Results";
}
<h2>Results</h2>
<fieldset>
<legend>UserViewModel</legend>
@foreach (var item in Model){
<div class="display-label">UserName</div>
<div class="display-field">@item.UserName</div>
<div class="display-label">LastActivityDate</div>
<div class="display-field">@String.Format("{0:g}", item.LastActivityDate)</div>
<div class="display-label">Address</div>
<div class="display-field">@item.Address</div>
<div class="display-label">City</div>
<div class="display-field">@item.City</div>
<div class="display-label">State</div>
<div class="display-field">@item.State</div>
<div class="display-label">Zip</div>
<div class="display-field">@item.Zip</div>
}
</fieldset>
我不斷收到此錯誤:
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
我想不通爲什麼。
我試過了,然後
constructor
設置得到這個錯誤:「對象引用不設置到對象的實例」這個錯誤發生在您張貼我要更改的行上。這就是拋出異常 – anthonypliu 2011-03-19 06:12:54
@anthonypliu,我從我的例子中刪除不需要的'AsEnumerable()'作爲ToList()已經是Enumerable。查看視圖代碼可能是因爲String.Format(),LastActivityDate可能爲null並導致NullReferenceException。它應該工作。否則,進入代碼並找到空引用 - 最有可能是用戶對象或視圖中的某些東西。 – 2011-03-19 06:19:47
我試過,但它沒有工作,我想我知道問題的一部分,我的第一個視圖沒有正確發佈ProfileQuery模型,因爲我試圖打印profileQuery.SearchString,並且我得到一個空的異常,所以SearchString甚至沒有通過到HttpPost – anthonypliu 2011-03-19 06:22:58