微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Asp.Net MVC防止重复记录

如何解决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);
         
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。