Asp.NetMVC防止重复记录



如何防止mvc c#中的重复输入?我的主键是";Locatie";

我的代码(控制器(:

// GET: Parts/Create
public ActionResult Create()
{
return View();
}
// POST: Parts/Create
// To protect from overposting attacks, enable the specific properties you want to bind to, for 
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "NaamComponent,Locatie,Waarde,Bestelnummer,ManufacturerPN,Omschrijving")] Parts parts)
{
if (ModelState.IsValid)
{
db.Parts.Add(parts);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(parts);
}

在控制器中使用以下代码:

public ActionResult Create([Bind(Include = "NaamComponent,Locatie,Waarde,Bestelnummer,ManufacturerPN,Omschrijving")] Parts parts)
{
if (ModelState.IsValid)
if (db.Parts.Any(part => part.Locatie == parts.Locatie))
{
ModelState.AddModelError("", "Locatie naam is bezet.");
}
else
{
db.Parts.Add(parts);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(parts);

}

最新更新