Reputation: 109
How do I display error messages in MVC4 when a condition is or isn't met?
I have this block of code in my controller
[HttpPost]
public ActionResult DeleteOwner(int OwnerID)
{
Owner dbEntry = _DBContext.Owners.Find(OwnerID);
if (dbEntry != null)
{
if (dbEntry.GroupTypes.Count == 0)
{
_DBContext.Owners.Remove(dbEntry);
_DBContext.SaveChanges();
}
else
{
//Throw a validation message
}
}
return RedirectToAction("GetListOfOwners");
}
The above block of code stops a user form deleting any owner from the database who has at least one or greater associated GroupTypes.
It works but at present it's just returning the user back to the page, what I'd like to know is how would I display an appropriate error message which tells the user why the owner hasn't been removed?
Thanks in advance for any help.
Upvotes: 0
Views: 1537
Reputation: 13248
You can use the following to add errors, then display them on the view:
else
{
ModelState.AddModelError("", "Your message here");
return View("NameOfView");
}
On the view, add @Html.ValidationSummary()
to display the errors.
Upvotes: 2