0

I'm trying to implement an error handling mechanism in my MVC project. I'm looking for a way to display the error message to the user on the same page. I've tried -

returning JavaScript(..) - However, this does not work as I'm calling the action through an ActionLink and not Ajax.I cannot call it through Ajax as error may have been generated even when the page loads for the 1st time.

returning Content(..) - This doesn't show an alert either

I do this in a catch block -

public ActionResult Index()
{
    try
    {
        //something that generates an exception
    }
    catch(Exception e)
    {
        //show an alert with the error through JS
    }
}

Is there any way of executing javascript to display an error to the user without using an Ajax call to execute the action?

Community
  • 1
  • 1
neuDev33
  • 1,573
  • 7
  • 41
  • 54

1 Answers1

1

You can do something like

    catch(Exception e) 
    {
       ViewBag.Error = "error:" + e.ToString();
    }

    return View();

In your view bind like

    <%if(ViewBag.Error != null) 
    {%>
      <script type="text/javascript">
        alert('<%=ViewBag.Error%>');
      </script>
    <%}%>
Kunal Ranglani
  • 408
  • 3
  • 14
  • I have to send this error message to the parent controller to display. so storing it in ViewBag of this controller will not work. And Rediercting to the parent controller with the error passed as a parameter does not work either. I've been thinking about it, and JS seems the only way out right now. – neuDev33 Jul 09 '12 at 21:50
  • ViewBag is in ControllerBase so it should be visible to any inherited controller. What do you mean by cannot send this message to parent controller. Any value you put in ViewBag in your child controller should be accessible by your parent controller if the controller handing this request is inherited from Parent. Could you show you controller class heirarchy? – Kunal Ranglani Jul 09 '12 at 21:58