0

I'm need add ChapterObject to list in CourceModel, but i'm don't know why value ChapterObject not assign to current entity.

I try, but this not work.

my first method.

    [HttpGet]
    public ActionResult CreateChapter(CourceModel courceModel)
    {
        var chapterObject = new ChapterObject();
        _db.CourceModels.Find(courceModel.Id).ChapterObjects.Add(chapterObject);
        _db.Entry(chapterObject).State = EntityState.Modified;
        return View(chapterObject);
    }
    [HttpPost]
    public ActionResult CreateChapter(ChapterObject chapterObject)
    {
        _db.Entry(chapterObject).State = EntityState.Detached;
        _db.SaveChanges();
        return RedirectToAction("Index");

    }

Second method

I'm try create field _courceModelId and add value in Get method, but when i'm call Post method _courceModelId = 0. I'm think what dispose remove _courceModelId value and I'm create new flag _isUptdated, but this not work too.

    private int _courceModelId;
    private bool _isUptdated;

    [HttpGet]
    public ActionResult CreateChapter(CourceModel courceModel)
    {
        _courceModelId = courceModel.Id;
        _isUptdated = true;
        var chapterObject = new ChapterObject();
        return View(chapterObject);
    }
    [HttpPost]
    public ActionResult CreateChapter(ChapterObject chapterObject)
    {
        //why _courceModelId = 0?
        _db.CourceModels.Find(_courceModelId).ChapterObjects.Add(chapterObject);
        _db.SaveChanges();
        _isUpdate = false;
        return RedirectToAction("Index");
    }
    protected override void Dispose(bool disposing)
    {
        if(_isUptdated) return;
        if (disposing)
        {
            _db.Dispose();
        }
        base.Dispose(disposing);
    }
Artem Tishchenko
  • 330
  • 1
  • 13

1 Answers1

0

Here you attach object(ChapterObject) and modified another object (CourceModels)

[HttpGet]
public ActionResult CreateChapter(CourceModel courceModel)
{
    var chapterObject = new ChapterObject();
    var courseModel = _db.CourceModels.Find(courceModel.Id);
     courseModel.ChapterObjects.Add(chapterObject);
    _db.Entry(courseModel).State = EntityState.Modified;
    return View(chapterObject);
}

And _courceModelId = 0 because it is not a static, and already begin another request. If you want to keep its value you have two options, Add it in model and submit it again in your form or add it in TempData

TempData["_courceModelId"] = courceModel.Id;
Ahmed
  • 1,542
  • 2
  • 13
  • 21