0

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)
Onick Ahmed
  • 91
  • 1
  • 15

2 Answers2

0

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 !!")]
Badhon Ashfaq
  • 851
  • 6
  • 9
0

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

Onick Ahmed
  • 91
  • 1
  • 15