The operation cannot be completed because the DbCo

2019-06-10 04:06发布

问题:

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

}