Search code examples
unique-constraintasp.net-mvc-5.2validationmessage

Get error message on isUnique attribute MVC


I have a model property like below,

[Index("CourseCodeIndex", IsUnique = true)]
[MaxLength(15)]
public string Name { get; set; }

and if I use invalid data it works well but returns no error message. Is there any way to show a message on (view, like other required like messages)

@Html.ValidationMessageFor(model => model.Name)

Solution

  • Make an instance of your context file

    private datbaseContext db = new databaseContext();
    

    add the code below to your controller action method

    db.table.Add(model);
                    var user = db.table.Where(u => u.Name == model.Name).FirstOrDefault();
                    if (user != null)
                    {
                        ModelState.AddModelError("", model.Name + " Already Exists");
                    }
                    else
                    {
                        db.SaveChanges();
                        return RedirectToAction("Index", "model");    
                    }
    

    And the @Html.ValidationSummary(true) from your view will attach the error message