Asp.Net MVC防止重复记录

问题描述

如何防止在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);
         
    }