1

I have a model Like :

public class Post
    {
        public int PostId { get; set; }
        public int ParentId { get; set; }
        public string PostTitle { get; set; }
        public IEnumerable<Post> ChildPosts { get; set; }
    }

I have also a add action in my Controller that return my above Model to add.cshtml view. Now come to the point my application running mode I get a exception (Like Database connection Exception). Now I want to display my exception message in add.cshtml page.

Is it possible? If yes. How can i done this work. Please explain with example code.

Mohammed Faruk
  • 495
  • 1
  • 9
  • 20

2 Answers2

4

If you want to show the error message on the same view:

[HttpPost]
public ActionResult Add(Post post)
{
    try
    {
        // do your database stuff ...
        return RedirectToAction("Success");
    }
    catch (SomeExceptionouNeedToHandle ex)
    {
        ModelState.AddModelError("", ex);
        return View(post);
    }
}

and inside your Add.cshtml view you could use the ValidationSummary helper to display the error message:

@Html.ValidationSummary()

Another possibility is to have a generic error page which will be shown when some unexpected exception occurs. Normally you should catch only exceptions that you want to handle. It's bad practice to catch general exceptions in a controller action.

Here's an example of exception handling.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • this would show the DBExceptions? Why i should use it like this? – hackp0int Jul 08 '12 at 07:28
  • 1
    You are correct. I was actually still editing my answer. It is bad practice to catch general exceptions. I have updated my answer now. General unhandled exceptions should probably be handled separately and displayed in a specific error view. – Darin Dimitrov Jul 08 '12 at 07:30
  • I still wouldn't use it in the view although it's good way to fix errors but i would put in log files because google may scan the bug and it's not good, talking from personal experience. – hackp0int Jul 08 '12 at 09:02
  • Correct, technical errors shouldn't be displayed, only business validation errors. – Darin Dimitrov Jul 08 '12 at 10:11
0

I would suggest you using the Elmah exception handling, you can check out these two links that i gave you.

link 1

link2

Community
  • 1
  • 1
hackp0int
  • 4,052
  • 8
  • 59
  • 95