ObjectContext实例已被释放,不能再用于需要连接错误级联下拉列表的操作

时间:2014-12-20 14:53:41

标签: c# jquery asp.net asp.net-mvc asp.net-mvc-4

我尝试在MVC4中级联下拉列表。 我有2个下拉列表1 - 类别 2 - 子类别。

当用户创建新产品时,他需要选择Category,然后选择与该类别相关的SubCategory。 我和杰森一起使用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内部获取类别名称我得到一个erorr并在控制台中我看到此错误:500服务器错误: ObjectContext实例已被释放,不能再用于需要连接的操作。

我需要做什么?

1 个答案:

答案 0 :(得分:5)

在序列化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
    };        
}