在 MVC 中,编辑功能遗漏了外键

In MVC, Edit function misses the Foreign Key

我有一个编辑屏幕,但出现错误。用户可以编辑对象,但外键为空。而且,这会导致一个巨大的问题。为什么它没有获得外键?这是我的代码...

第一个函数是完美的,但是带有HttpPost 的那个失去了TcmbCurrencyId 的值,这是一个外键。我该如何解决这个问题?

    public ActionResult Edit(int? Id)
    {
        if (Id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        TmcbExchangeRate rate = db.TmcbExchangeRate.Where(x=>x.Id==Id).First();

        if (rate == null)
        {
            return HttpNotFound();
        }

        return View(rate);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Id,TcmbCurrencyId,RateDate,ForexBuying,ForexSelling,BanknoteBuying,BanknoteSelling")] TmcbExchangeRate tmcbExchangeRate)
    {
        if (ModelState.IsValid)
        {
            db.Entry(tmcbExchangeRate).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(tmcbExchangeRate);
    }

您可能没有将请求的 属性 TcmbCurrencyId 包括在您提交时要 post 编辑的视图中。如果不是,则在提交时不会 posted 到控制器。只有表单中使用的值在提交时 posted 到控制器。鉴于您没有在原始 post 中包含视图,那么这是一个假设。

将此添加到视图中的表单中

@Html.HiddenFor(model => model.TcmbCurrencyId)