The operation cannot be completed because the DbContext has been disposed In Mqsql and Entity Framework

限于喜欢 提交于 2019-12-08 09:21:41

问题


I am doing From dropdown selection, I fill textboxes with the Json Value. Action() Method work fine It return Json value but page not populate these value to TextBoxes control. When i use Developer Tool then i get, it throw a Error "The operation cannot be completed because the DbContext has been disposed."

Controller

    private hcEntities db = new hcEntities();

 // GET: Chains
 public ActionResult Index()
{
    ViewData["chain_name"] = new SelectList(db.chains, "code", "name");
    return View(db.chains.ToList());
}

//Action Function callby javascript
[HttpPost]
public ActionResult Action(string code)
{
    using (var ObjDb = new hcEntities())
    {
        var query = from c in ObjDb.chains
            where c.code == code
            select c;
        return Json(query);//Return Json Result
    }
}

View:-

<script type="text/javascript">
function Action(code) {
$.ajax({
    url: '@Url.Action("Action", "Chains")',
    type: "POST",
    data: { "code": code },
    "success": function (data) {
        if (data != null) {
            var vdata = data;
            $("#ChainName").val(vdata[0].name);
            $("#ChainCode").val(vdata[0].code);
            $("#username").val(vdata[0].username);
        }
    }
});
}

回答1:


Try return Json(query.FirstOrDefault());




回答2:


Use IDisposable again in the GET Controller:

 // GET: Chains
public ActionResult Index()
{
    using (var ObjDb = new hcEntities())
    {
       ViewData["chain_name"] = new SelectList(ObjDb.chains, "code", "name");
       return View(ObjDb.chains.ToList());
    }

}


来源:https://stackoverflow.com/questions/26093729/the-operation-cannot-be-completed-because-the-dbcontext-has-been-disposed-in-mqs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!