Search code examples
.netasp.net-mvc-3c#-4.0argumentexception

ArgumentException Message displayed in a Label


    public void DeleteUser(User user)
    {
        if (!UserExists(user))
            throw new ArgumentException("User doesn't exist!");
        else
        {
            MatrixDb.Users.Remove(user);
            MatrixDb.SaveChanges();
        }
    }

I want to show that "ArgumentException" message in a proper way on the page; I want it inside the ValidationSummary Helper or a Label, so that when the User faces it, they are not sent to 'Server Error in '/' Application' Page rather, the error is shown in some Controller, like a Label or Textfield.

Is this even possible?! Because on the Server Page that's shown when the ArgumentException is raised, does show that message there!


Solution

  • Controller:

        [HttpPost]
        public ActionResult Test(User user)
        {
    
            try
            {
                Delete(user);
            }
            catch (Exception e)
            {
                ViewData["error"] = e.Message; //ViewBag.error = e.Message can be used too        
            }
            return View();
        }
    

    View:

    @if (ViewData["error"] != null) //ViewBag.error != null  
    {
       <h2>@ViewData["error"].ToString()</h2> //@ViewBag.error.ToString() if ViewBag is used
    }