Entity Framework で MVC 3 を学習していますが、コントローラーの削除アクションの結果メソッドに問題があります。削除用の 2 つの ActionResult メソッドがあります。1 つは [HttpPost] を使用してデータをデータベースに送信し、もう 1 つは ID に基づいて正しいレコードをビューに入力します。
私の問題は、パラメーターに null オブジェクトがあるため、削除トランザクションをコミットしようとすると、null 値を持つ null オブジェクトがあるため、正しい値が表示されないことです。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DBFirstMVC.Models;
namespace DBFirstMVC.Controllers
{
public class BrandController : Controller
{
// Instantiate model of my database when controller is called
//TestBradEntities db = new DBFirstMVC.Models.TestBradEntities();
//
// GET: /Brand/
public ActionResult Index()
{
using (var db = new DBFirstMVC.Models.TestBradEntities1())
{
return View(db.Brands.ToList());
}
}
//
// GET: /Brand/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /Brand/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Brand/Create
[HttpPost]
public ActionResult Create(Brand brand)
{
using (var db = new DBFirstMVC.Models.TestBradEntities1())
{
db.Brands.Add(brand);
db.SaveChanges();
}
return RedirectToAction("Index");
}
//
// GET: /Brand/Edit/5
public ActionResult Edit(int id)
{
try
{
using (var db = new DBFirstMVC.Models.TestBradEntities1())
{
return View(db.Brands.Find(id));
}
}
catch (Exception ex)
{
return View(ex.ToString());
}
}
//
// POST: /Brand/Edit/5
[HttpPost]
public ActionResult Edit(int id, Brand brand)
{
try
{
using (var db = new DBFirstMVC.Models.TestBradEntities1())
{
db.Entry(brand).State = System.Data.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (Exception ex)
{
return View();
}
}
//
// GET: /Brand/Delete/5
public ActionResult Delete(int id)
{
using (var db = new DBFirstMVC.Models.TestBradEntities1())
{
return View(db.Brands.Find(id));
}
}
//
// POST: /Brand/Delete/5
[HttpPost]
public ActionResult Delete(int id, Brand brand)
{
try
{
using (var db = new DBFirstMVC.Models.TestBradEntities1())
{
db.Entry(brand).State = System.Data.EntityState.Deleted;
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
これは、null オブジェクトを含むコードです。
[HttpPost]
public ActionResult Delete(int id, Brand brand)
ブランドが無効で、その理由がわかりません。例えば
[HttpPost]
public ActionResult Edit(int id, Brand brand)
Edit actionresult の Brand Parameter には、オブジェクトにデータがあり、null 値ではありません。
これを修正する方法を知っている人はいますか?ありがとう。