ObjectContext实例已被处置,不能再用于需要连接错误级联下拉列表的操作 [英] The ObjectContext instance has been disposed and can no longer be used for operations that require a connection error cascade dropdown list
问题描述
我尝试在MVC4中级联dropdownlist. 我有2个下拉列表1-类别 2-子类别.
i try to cascade dropdownlist in MVC4. i have 2 dropdown list 1 - Category 2 - SubCategory.
用户创建新产品时,他需要选择类别,然后选择与该类别相关的子类别. 我将ajax与jason一起使用.
When the user create new product he need to choose Category and then a SubCategory that related to the category. i use ajax with jason .
public ActionResult Create()
{
List<Category> allcategories = new List<Category>();
List<SubCategory> allSubCategories = new List<SubCategory>();
using (WebStoreEntities1 db1 = new WebStoreEntities1())
{
allcategories = db1.Categories.OrderBy(x => x.CategoryName).ToList();
}
ViewBag.categoryID = new SelectList(db.Categories, "CategoryId", "CategoryName");
ViewBag.SubCategoryID = new SelectList(allSubCategories, "SubCategoryId", "SubCategoryName");
return View(main);
}
在html页面中的Jquery代码:
in the html page the Jquery code:
$(document).ready(function () {
var $SubCategoryID = $('#SubCategoryID');
$('#CategoryID').change(function () {
var CategoryID = $('#categoryID').val();
if (!isNaN(CategoryID)) {
var ddCategory = $("#SubCategoryID");
ddCategory.empty();
ddCategory.append($("<option></option>").val("").html("Sub Category!"));
$.ajax({
type: 'GET',
url: '@Url.Action("GetSubCategories", "StoreManager")',
data: { CategoryID: CategoryID },
//dataType: "json",
success: function (data) {
console.log('success',data)//for test
$.each(data, function (i, val) {
ddCategory.append(
//$SubCategoryID.append(
$('<option></option>').val(val.SubCategoryId).html(val.SubCategoryName)
);
});
},
error: function () {
alert("Error");
}
});
}
});
});
和代码处理此请求是:
[HttpGet]
public JsonResult GetSubCategories(string categoryID )
{
List<CategoryToSubCategory> allSubCategory = new List<CategoryToSubCategory>();
int id = 0;
if (int.TryParse(categoryID,out id))
{
using(WebStoreEntities1 db1 = new WebStoreEntities1())
{
allSubCategory = db1.CategoryToSubCategories.Where(a => a.CategoryId.Equals(id)).OrderBy(a => a.SubCategory.SubCategoryName).ToList();
}
}
if (Request.IsAjaxRequest())
{
return new JsonResult
{
Data=allSubCategory,
JsonRequestBehavior=JsonRequestBehavior.AllowGet
};
}
else
{
return new JsonResult
{
Data="error"
};
}
}
CategoryToSubCategory模型:
The CategoryToSubCategory Model:
public partial class CategoryToSubCategory
{
public int CategoryToSubId { get; set; }
public int CategoryId { get; set; }
public int SubCategoryId { get; set; }
public Nullable<int> ProductId { get; set; }
public virtual Product Product { get; set; }
public virtual SubCategory SubCategory { get; set; }
}
所有工作,但在html中插入以获取类别名称,我得到了erorr,在控制台中,我看到此错误:500服务器错误: ObjectContext实例已被处置,不能再用于需要连接的操作.
all work but in the html insted to get the category name i get an erorr and in the console i see this error: 500 server error: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
我需要做什么?
推荐答案
序列化json响应时,代码将尝试延迟加载并序列化Product and
SubCategory`.您可以使用Select语句,通过将查询结果投影到仅包含SubCategoryId和SubCategoryName的匿名类型中来解决此问题.
When serializing the json response the code will try to lazy load and serialize Product and
SubCategory`. You can fix it by projecting the result of your query into an anonymous type that just contains SubCategoryId and SubCategoryName, using a Select statement.
该想法将在您的GetSubCategories
方法中应用为:
The idea would be applied in your GetSubCategories
method as:
using(WebStoreEntities1 db1 = new WebStoreEntities1())
{
allSubCategory = db1.CategoryToSubCategories
.Where(a => a.CategoryId.Equals(id))
.OrderBy(a => a.SubCategory.SubCategoryName)
.Select(a => new {
SubCategoryId = a.SubCategoryId,
SubCategoryName = a.SubCategory.SubCategoryName })
.ToList();
}
因此,由于该方法的类型是匿名类型,因此您现在不再可以在方法开始时声明allSubCategory
变量.
但是,您可以将方法更改为:
So now you can no longer declare the allSubCategory
variable at the beggining of the method as its type is an anonymous type.
You can however change your method as:
[HttpGet]
public JsonResult GetSubCategories(string categoryID )
{
int id = 0;
if (Request.IsAjaxRequest() && int.TryParse(categoryID,out id))
{
using(WebStoreEntities1 db1 = new WebStoreEntities1())
{
var allSubCategory = db1.CategoryToSubCategories
.Where(a => a.CategoryId.Equals(id))
.OrderBy(a => a.SubCategory.SubCategoryName)
.Select(a => new {
SubCategoryId = a.SubCategoryId,
SubCategoryName = a.SubCategory.SubCategoryName })
.ToList();
return new JsonResult
{
Data=allSubCategory,
JsonRequestBehavior=JsonRequestBehavior.AllowGet
};
}
}
return new JsonResult
{
Data="error",
JsonRequestBehavior=JsonRequestBehavior.AllowGet
};
}
这篇关于ObjectContext实例已被处置,不能再用于需要连接错误级联下拉列表的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!