我尝试在 MVC4 中级联下拉列表。 我有 2 个下拉列表 1 - 类别 2 - 子类别。
当用户创建新产品时,他需要选择类别,然后选择与该类别相关的子类别。 我将 ajax 与杰森一起使用。
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 代码:
$(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 模型:
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 中获取类别名称时出现错误,在控制台中我看到此错误:500 服务器错误: ObjectContext 实例已被释放,不能再用于需要连接的操作。
我需要做什么?
最佳答案
当序列化 json 响应时,代码将尝试延迟加载和序列化 Product and
SubCategory`。您可以通过使用 Select 语句将查询结果投影到仅包含 SubCategoryId 和 SubCategoryName 的匿名类型来修复它。
这个想法将在您的 GetSubCategories
方法中应用为:
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
变量,因为它的类型是匿名类型。
但是,您可以将方法更改为:
[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
};
}
关于c# - ObjectContext 实例已被处置,不能再用于需要连接错误级联下拉列表的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27581352/