In this article I will explain with an example, how to return Exception Error Message when using JSON and AJAX in ASP.Net MVC Razor.
This article will illustrate how to return the Exception Error Message using JSON from the Controller when calling the Controller using jQuery AJAX in ASP.Net MVC Razor.
Note: For beginners in jQuery AJAX and ASP.Net MVC, please refer my article ASP.Net MVC: jQuery AJAX and JSON Example.
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling AJAX POST operation
This Action method handles the AJAX Form submission and it accepts the value of the Form elements as parameter.
The value of the Age is converted into an Integer. If this conversion is successful, then a JSON object with a property result set with Boolean value TRUE is returned.
In case when the value of Age is not a valid Integer value, an exception occurs.
Then a JSON object with properties i.e. error (containing the exception message) and result (set with Boolean FALSE value) is returned.
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult AjaxMethod(string name, string age)
    {
        try
        {
            int personAge = int.Parse(age);
            return Json(new { result = true });
        }
        catch (Exception ex)
        {
            return Json(new { result = false, error = ex.Message });
        }
    }
}
 
 

View
The View consists of two TextBox fields created for capturing values for Name and Age.
There’s also an HTML Button at the end of the Table which has been assigned with a JavaScript OnClick event handler.
When the Submit Button is clicked, the value of Name and Age TextBoxes are passed to the AjaxMethod Action method using jQuery AJAX call.
Once the response is received, the value of the result property is evaluated.
If the value is TRUE, then a success message is displayed using JavaScript Alert Message Box.
And if the value is FALSE, the value of the error property is displayed using JavaScript Alert Message Box.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <table>
        <tr>
            <td>Name: </td>
            <td><input type="text" id="txtName"/></td>
        </tr>
        <tr>
            <td>Age: </td>
            <td><input type="text" id="txtAge"/></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="button" value="Submit" onclick="AjaxFormSubmit()"/></td>
        </tr>
    </table>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <script type="text/javascript">
        function AjaxFormSubmit() {
            var person = {};
            person.Name = $("#txtName").val();
            person.Age = $("#txtAge").val();
            $.ajax({
                type: "POST",
                url: "/Home/AjaxMethod",
                data: JSON.stringify(person),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.result == true) {
                        alert("Form submitted!");
                    }
                    else {
                        alert(response.error);
                    }
                }
            });
        }
    </script>
</body>
</html>
 
 
Screenshot
ASP.Net MVC: Return Exception Error Message when using JSON and AJAX
 
 
Browser Compatibility

The above code has been tested in the following browsers.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Downloads