Show Asp.Net Exception Error Message in AJAX(JQuery) Call Error Function in C#

Introduction:
This article explains how to show asp.net exception error message in jQuery ajax web method calls using error function in c# or get error message in jQuery ajax post method in asp.net using c# or jQuery show custom error message during ajax calls in asp.net using c#.

Aspx Page:


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>jQuery Get Original Asp.net Exception Message in Ajax Method</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function () {
$('#btnSum').click(function () {
var val1 = $.trim($('#txtVal1').val());
var val2 = $.trim($('#txtVal2').val());
$.ajax({
type: "POST",
url: "GetExceptionMessageinjQuery.aspx/GetSumofNumbers",
data: "{'val1':'" + val1 + "', 'val2':'" + val2 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$('#lblMessage').text(response.d)
},
error: function (data) {
var r = jQuery.parseJSON(data.responseText);
var errorMessage = r.Message;
var exceptionType = r.ExceptionType;
var stackTrace = r.StackTrace;
$('#divStatus').html("<b>Error Message: </b>" + errorMessage + 
"</br></br>" + "<b>ExceptionType: </b>" + exceptionType + "</br></br>" + 
"<b>Asp.Net StackTrace: </b>" + stackTrace)
}

});
return false;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr><td>First Number:</td><td><input type="text" id="txtVal1" /></td></tr>
<tr><td>Second Number:</td><td><input type="text" id="txtVal2" /> </td></tr>
<tr><td>SUM:</td><td><label id="lblMessage"/></td></tr>
<tr><td colspan="2"><input type="button" id="btnSum" value="Get Sum" /></td></tr>
</table>
<hr />
<div id="divStatus"></div>
</div>
</form>
</body>
</html>

C# Code:

using System;
using System.Web.Services;

protected void Page_Load(object sender, EventArgs e)
{

}
[WebMethod]
public static int GetSumofNumbers(int val1, int val2)
{
return val1 + val2;
}

OutPut: 

error
Ashwani
Ashwani

This is a short biography of the post author. Maecenas nec odio et ante tincidunt tempus donec vitae sapien ut libero venenatis faucibus nullam quis ante maecenas nec odio et ante tincidunt tempus donec.

No comments:

Post a Comment