Pankaj
Pankaj

Reputation: 10115

500 Internal Server Error When sending POST request from jquery to controller

Controller Code

public ActionResult SearchByUPC_Name(String keyword)
{
    using (DbPOSEntities db = new DbPOSEntities())
    {
        var CompanyID = ((UserModel)Session["User"]).CompanyID;
        var items = db.tblItems.Where(i => i.CompanyID == CompanyID 
                        && i.IsDeleted == false 
                        && (i.UPC == keyword || i.Name.Contains(keyword))).ToList();
        return Json(new { Success = true, Items = items });
    }
}

Js Code

$.ajax({
    url: "/Item/SearchByUPC_Name",
    type: "POST",
    async: true,
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({ "keyword": searchStr }),
    dataType: "json",
    success: function (response) {
        debugger;
        if (response.Success) {
            console.log('ok');
        }
        else {
            console.log('not ok');
        }
    },
    error: function (err) {
        alert(err.statusText);
    }
});

I got this error: 500 Internal Server Error : The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

Upvotes: 0

Views: 655

Answers (1)

kkakkurt
kkakkurt

Reputation: 2800

Your using wrap can cause this error because of Entity Framework's lazy-loading attribute. And it disposes context before entities are returned.

using (DbPOSEntities db = new DbPOSEntities())
    {
        var CompanyID = ((UserModel)Session["User"]).CompanyID;
        var items = db.tblItems.Where(i => i.CompanyID == CompanyID 
                        && i.IsDeleted == false 
                        && (i.UPC == keyword || i.Name.Contains(keyword))).ToList();
        return Json(new { Success = true, Items = items });
    }

You could remove using wrap to use eager loading for avoid the error you are facing:

DbPOSEntities db = new DbPOSEntities();
var CompanyID = ((UserModel)Session["User"]).CompanyID;
var items = db.tblItems.Where(i => i.CompanyID == CompanyID 
                    && i.IsDeleted == false 
                    && (i.UPC == keyword || i.Name.Contains(keyword))).ToList();
return Json(new { Success = true, Items = items });

Upvotes: 1

Related Questions