Validate data duplication with data annotation

0

I have a table in bd sql sever called article with fields IdArticulo, CodArticulo, DesArticulo, IsActivo ... in my mvc project valid almost all fields with data.annotation ... for example IdArticulo with, CodArticulo with ... but I do not know how to validate the field CodArticulo that is unique in the BD ... For example, I entered an item in this way:

IdArticulo   CodArticulo   DesArticulo   IsActivo
   1            A001      GALLETA SODA      1

Up there all right ... but if I want to enter another item with the same code (A001) ... how could data.annotation verify that a duplicate record is being entered?

Remember that the CodArticle field is unique and when validating it should return a

  

ErrorMessage:="An item with the same code already exists"

I hope your help.

Thank you.

    
asked by edusito87 26.12.2017 в 16:36
source

1 answer

1

Friend the problem in this case is that you need to validate data that are in BD so you must necessarily make a query to check if it already exists in your database. You can in your controller, when calling the POST method validate if it already exists. example:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="IdArticulo, CodArticulo, DesArticulo, IsActivo")] Articulo articulo)
{

    if (db.Articulos.Any(a => a.CodArticulo == articulo.CodArticulo))
    {
        ModelState.AddModelError("CodArticulo", "Ya existe un artículo con este código");
    }
    if (ModelState.IsValid)
    {
        db.Articulos.Add(articulo);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(articulo);
}

As you can see before the condition to Save the Article I added another condition in which I ask if there already exists an article in bd with that code, if so I call ModelState.AddModelError() and I pass it as parameters the field to be validated ( "CodArticulo") and the message that I want to show "....". In this way valid, I hope it helps you

    
answered by 26.12.2017 в 19:18