Get error message on isUnique attribute MVC

1.2k Views Asked by At

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)
2

There are 2 best solutions below

0
On BEST ANSWER

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

0
On

if you want to show the error message, you need to declare it like:

[Required(ErrorMessage = "Compiletime error required")]

Also, try this.

 [Unique(ErrorMessage = "This already exist !!")]