Search code examples
ajaxdbcontextasp.net-core-2.2

DBContext error when attempting to edit/update


When performing inline edit in a jquery/jqgrid table, I am seeing the ID (PK) and the column values come across to my public IActionResult Edit URL with a 200 response. However I am then encountering an error where my DBContext does not exist, however it's the same dbcontext I used to retrieve the data. Also, not able to return a string message? The code up until my Edit works, what am I doing wrong?

namespace MyProject.Controllers
{
    public class CheckRequestController : Controller
    {
        private readonly MyDBContext _context;

        public CheckRequestController(MyDBContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult LoadData()
        {
            try
            {
                var fileData = (from tempFile in _context.CheckRequest
                                select tempFile);
                var data = fileData.ToList();
                return Json(data);
            }
            catch (Exception)
            {
                throw;
            }
        }

        // I'm trying to run an update to the row in SQL Server.  I see my ID and the values come across 200 status but can't update.. Also can't return string from IAction
        // Also can't return string from IActionResult or ActionResult. How to return message if failure
        public IActionResult Edit(CheckRequest checkrequests)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (MyDBContext db = new MyDBContext())
                    {
                        db.Entry(checkrequests).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                //msg = "Error occured:" + ex.Message;
                var msg = new string[] { "Error occured:" + ex.Message };
            }
            return msg;
        }
    }
}

Solution

  • I removed the readonly and was able to trace the server and see the request coming across; can't believe my eyes didn't catch that. Still curious how to capture and return an error message that's useful though on the return in the IActionResult. Right now I changed it to return Ok() so it's not really useful if an error is to occur.