3

I have defined a method in try catch block in HomeController.cs in my MVC3 Razor project. Now please tell how wil I show this exception message on my view page?

1
  • Please add code snippet what you tried. or error log if you are getting any error. Commented Feb 7, 2014 at 5:46

4 Answers 4

10

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

[HttpPost]
public ActionResult Add(Model model)
{
    try
    {
        // some code...
        return RedirectToAction("Success");
    }
    catch (SomeException ex)
    {
        ModelState.AddModelError("", ex.Message);
        return View(model);
    }
}

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

@Html.ValidationSummary()
Sign up to request clarification or add additional context in comments.

Comments

0

add model state error in HomeController.cs file catch section like

  try
  {
        methodThrowsError();
  }
  catch(SomeException ex)
  {
     ModelState.AddModelError("", ex);
  }
 return View(yourmodel);

and in cshtml page display error like

    @Html.ValidationSummary()

Here's an example of exception handling.

Comments

0

Just create a session variable in your controller AS :

public ActionResult DeleteConfirmed(int id)
    {
   try
        {
            //////whatever code u want
            return RedirectToAction("Index");
        }
        catch (Exception ex)
        {
            string m="mysession";
            Session["dep"] = m;}
return view();}

and use it as a flag variable.. then in your razor view Show your message as :

 if (Session["dep"] != null)
 { 
    <h1>Whatever message you want to show in your view</h1>

 }

Rate my answer please if it was helpfull

Comments

0
[HttpPost]
public ActionResult MethodName(Model model)
{
    try
    {
        // your business logic if need
        return RedirectToAction("Success");
    }
    catch (Exception ex)
    {
        ModelState.AddModelError("", ex.Message);
        return View(model);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.