The operation cannot be completed because the DbCo

2019-06-10 03:36发布

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);
        }
    }
});
}

2条回答
\"骚年 ilove
2楼-- · 2019-06-10 04:28

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());
    }

}
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-06-10 04:30

Try return Json(query.FirstOrDefault());

查看更多
登录 后发表回答