How to Catch An Ajax error while using Jquery UI tabs along with Custom Error handler - asp.net-mvc

I am using Jquery UI tabs in my asp.net mvc web application. I have my tabs working good.
But, the problem is when ever an ajax errors happens, it should be caught and JSON response should be thrown back.
I am using an CustomError handler over riding MVC HandleError Attribute as follows:
public class CustomHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
{
return;
}
if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500)
{
return;
}
if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
{
return;
}
// if the request is AJAX return JSON else view.
if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
error = true,
message = filterContext.Exception.Message
}
};
}
else
{
var controllerName = (string)filterContext.RouteData.Values["controller"];
var actionName = (string)filterContext.RouteData.Values["action"];
var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
filterContext.Result = new ViewResult
{
ViewName = View,
MasterName = Master,
ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
TempData = filterContext.Controller.TempData
};
}
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}
So, if the error occurs and it is an ajax request , then the above method will throw the JSON response.
But,I am struggling to find out how to catch that JSON respnse and show it on Client Side.
Please help..I tried using ajaxoptions with UI Tabs as follows:
$(document).ready(function () {
$('#tabs').tabs({
activate: function (event, ui) {
ui.oldPanel.empty();
},
ajaxOptions: { success: Success, error: Failure }
});
$('#tabs').css('display', 'block');
$(function () {
$(this).ajaxStart(function () {
$("#ajaxLoading").show();
});
$(this).ajaxStop(function () {
$("#ajaxLoading").hide();
});
});
});
function Success(data) {
alert("Successfully loaded the tabs");
}
function Failure() {
alert("Some thing wrong had happened");
}
please help..on how to recieve that erronoeous JSON response and show an appropraite alert to the end user..

I found the solution as this:
$.ajaxSetup({
type: "GET",
cache: false,
error: function (e) {
var Error = e.responseText;
var ErrorCode= xx;
alert("Sorry, An Error has been occured while processing your request " + Error);
}
});
I have used ajaxSetup() to receive the response from Server Side.
Hope this helps...

Related

ASP.Net MVC, WebAPI, AngularJS - Check if value exists in database

I am using webapi and angularjs in my ASP.net MVC app. Everything is working good but in my insert (post) method I need to check if a value exists in the db before doing an insert. I am not sure where that should go. I ruled out the webapi because a void does not return a value. The logical place seems to be the controller, but I cannot find the right way to call my angular getEmployee(id) method from within the insert controller method. Any help is appreciated.
Angular controller (post):
$scope.insertEmployee = function (employee) {
employeeFactory.insertEmployee(employee)
.success(function (emp) {
$scope.employee = emp;
})
.error(function (error) {
$scope.status = 'Unable to load employee data: ' + error.message;
});
};
Angular factory (post):
factory.insertEmployee = function (employee) {
url = baseAddress + "employee/insert/";
$http.post(url, employee).success(function (data) {
alert("Saved Successfully!!");
}).error(function (data) {
$scope.error = "An Error has occured while saving employee! " + data;
});
};
webapi controller post method:
[Route("api/employee/insert/")]
public void Post(Employee employee)
{
if (ModelState.IsValid)
{
context.Employee.Add(employee);
context.SaveChanges();
}
}
Angular controller (get):
$scope.getEmployees = function (term) {
employeeFactory.getEmployees(term)
.success(function (data) {
$scope.employees = data;
})
.error(function (error) {
$scope.status = 'Unable to load employee data: ' + error.message;
});
};
I would suggest doing this in your web-api server side. You can construct an exception and throw it. Some pseudo-code:
[Route("api/employee/insert/")]
public void Post(Employee employee)
{
if (ModelState.IsValid)
{
// verify doesn't already exist
if(...item-already-exists...) {
var resp = new HttpResponseMessage(HttpStatusCode.Conflict)
{
Content = new StringContent("Employee already exists!")),
ReasonPhrase = "Employee already exists!"
}
throw new HttpResponseException(resp);
}
context.Employee.Add(employee);
context.SaveChanges();
}
}
Your factory doesn't match your controller. If you want to use success and error from employeeFactory.insertEmployee, it needs to return the promise:
factory.insertEmployee = function (employee) {
url = baseAddress + "employee/insert/";
return $http.post(url, employee);
};
So then you can do
employeeFactory.insertEmployee(employee).success( ... )
Now to answer your question you could either do a database read in insertEmployee to check if the value exists before you insert it. Or save a server call and do the check during the insert request: if the employee exists, return an error or a specific message to tell the client.
With the help of floribon and Nicholas Smith I managed to come up with a solution that bubbles the error up to my view, which I display in a div element. This is only bare bones, but is a start.
My angular controller:
$scope.insertEmployee = function (employee) {
employeeFactory.insertEmployee(employee)
.success(function (data) {
$scope.employee = data;
$scope.status = 'The item was saved';
})
.error(function (error) {
$scope.status = 'Unable to save the employee data: ' + error;
});
};
My angular factory:
factory.insertEmployee = function (employee) {
url = baseAddress + "employee/insert/";
return $http.post(url, employee);
};
my webapi controller:
[Route("api/employee/insert/")]
public HttpResponseMessage Post(Employee employee)
{
HttpResponseMessage response;
// check for the employee
var employeeCheck = context.Employee
.Where(b => b.EmployeeNumber == employee.EmployeeNumber)
.FirstOrDefault();
if (employeeCheck == null)
{
// save the item here
response = Request.CreateResponse(HttpStatusCode.OK);
}
else
{
response = Request.CreateResponse(HttpStatusCode.Conflict, "The item already exists");
}
return response;
}
The result is the message is "Unable to save the employee data: The item already exists".

Handling Ajax cal exceptions via Custom Action Filters

I am implementing an authorization mechanizm for my MVC application via Custom Action Filters.
I have provided the following Custom Action Filter for authorization:
[AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class AuthorizationFilterAttribute : ActionFilterAttribute
{
public AuthorizationEntity Entity { get; set; }
public AuthorizationPermission Permission { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
AuthorizationResult result = null;
// Base actions (Authentication first)
base.OnActionExecuting(filterContext);
BaseController controller = filterContext.Controller as BaseController;
if (controller != null)
{ // Base actions (Authorizatioın next)
User usr = controller.currentUser;
AuthorizationResult ar = AuthorizationManager.GetAuthorizationResult(this.Entity, this.Permission, usr.UserId, usr.RoleId);
if (!ar.IsAuthorized)
{
throw new UnauthorizedAccessException(ar.Description);
}
// Authorized, continue
return;
}
}
}
And in my Base Controller class I am handling UnauthorizedAccessException type Exceptions and redirect them to a warning page via the following code
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext.Exception is UnauthorizedAccessException)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
Exception ex = filterContext.Exception;
filterContext.ExceptionHandled = true;
filterContext.Result = new ViewResult()
{
ViewName = "UnauthorizedAccess"
};
}
else
{
throw filterContext.Exception;
}
}
}
This mechanism is OK for actions which return ActionResult. But I also have some AJAX calls, which I don't want to redirect to a warning page but would ilke to display a warning pop-up instead. Thi is why I have checked if the request is an Ajax call is not.
I am using the following code to make Ajax calls:
$.ajax({
type: "POST",
url: "AjaxPostMethodName",
dataType: "json",
data:
{
postval: [some value here]
},
success: function (msg) {
// Do some good actions here
},
error: function (x, t, m, b) {
// Display error
alert(m);
}
})
which goes to the following method on the Controller
public JsonResult AjaxPostMethodName(string postval)
{
try
{
// Some cool stuff here
return Json(null);
}
catch (Exception ex)
{
Response.StatusCode = UNAUTHORIZED_ACCESS_HTTP_STATUS_CODE;
return Json(ex.Message);
}
}
But when I fail the authorization check it directly shows the "Internal Server Error" message instead of falling to the catch block of AjaxPostMethodName method and displaying the proper message.
How can I make such code display filterContext.Exception instead of static "Internal Server Error" message?
Regards.
I finally found the answer to my solution in another Stack Overflow post (Can I return custom error from JsonResult to jQuery ajax error method?). I should use JsonExceptionFilterAttribute as follows:
public class JsonExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.ExceptionHandled = true;
string msg = filterContext.Exception.Message;
if (filterContext.Exception.GetType() == Type.GetType("System.UnauthorizedAccessException"))
{
msg = "Unauthorized access";
}
filterContext.Result = new JsonResult
{
Data = new
{
errorMessage = msg
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
}
Your OnException method will get called when there is Unhandled exception in your code. And in your ajax method AjaxPostMethodName you have put your code in try catch blcok. So any exception in this method will not go to your OnException method.
I've just checked the Response.StatusCode behavior and for me it works.
Index.cshtml
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script type="text/javascript">
$(document).ready(function () {
alert('doc ready');
$.ajax({
type: "POST",
url: '#Url.Action("AjaxPostMethodName")',
dataType: "json",
data:
{
test: '10'
},
success: function (msg) {
// Do some good actions here
alert('success');
alert(msg);
},
error: function (x, t, m, b) {
// Display error
alert('error');
}
});
});
</script>
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult AjaxPostMethodName(string postval)
{
Response.StatusCode = 401;
return Json("test");
}
}
}
When I set Response.StatusCode to 200 it calls success, when 401 it calls error.
Please verify whether other parts of your code don't interfere with it somehow.
You could try also following workaround - if AjaxPostMethodName throws exception returned JSON has a flag isValid and a message errorMessage, so in your ajax success method you can just check whether isValid is okay and handle error.

Posting form data from Partial view to controller using ajax

I have a jquery grid that has a list of Employee Records.To edit the records there is a link on each row.On click of that A jquery model popup opens and loads the partial view to show and edit the data.But on click of the button(custom button not the jquery model button) on the popup(that loads a partial view),the client side validation using dataAnnotation does not work. If I make a submit form like:-
$("#btnUpdate).submit(function (e) {
e.preventDefault();
var $form = $(this);
if ($form.valid()) {
//Add ajax call
}
});
Then after submit it redirects to:- { ../Employee/Edit/EmployeeId } where it shows a blank screen as I dont have any view for this.
I want that after the form post it should just refresh the jquery grid.
public PartialViewResult _CreateSupplier()
{
return PartialView(new Supplier());
}
[HttpPost]
public JsonResult _CreateSupplier(Supplier model)
{
//Validation
return Json(new
{
status = transactionStatus,
modelState = ModelState.GetModelErorrs()
}, JsonRequestBehavior.AllowGet);
}
Form post jquery method
$('#create-supplier').submit(function (e) {
e.preventDefault();
var $form = $(this);
if (!ModelIsValid($form))
return;
AjaxPost($form.serialize(), '#Url.Action("_CreateSupplier")', function (result) {
if (result.status == 0) {
$form[0].reset();
//Success
var grid = $("#gridSupplier").data("kendoGrid");
grid.dataSource.read();
} else if (result.status == 1)
AddFormErrors($form, result);
else if (result.status == 2)
//error;
});
});
Checking model method is valid and if invalid adding errors to form
function ModelIsValid(form) {
var validator = $(form).validate(); // obtain validator
var anyError = false;
form.find("input").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
if (anyError)
return false; // exit if any error found
return true;
}
function AddFormErrors(form, errors) {
for (var i = 0; i < errors.modelState.length; i++) {
for (var j = 0; j < errors.modelState[i].errors.length; j++) {
var val = $(form).find("[data-valmsg-for='" + errors.modelState[i].key + "']");
if (val.html().length > 0) {
$(form).find("[for='" + errors.modelState[i].key + "']").html(errors.modelState[i].errors[j]);
} else {
val.html('<span for="' + errors.modelState[i].key + '" generated="true" class="" style="">' + errors.modelState[i].errors[j] + '</span>');
}
}
}
}
Ajax post method:
function AjaxPost(postData, url, callback) {
$.ajax({
url: url,
type: 'POST',
data: postData,
dataType: 'json',
success: function (result) {
if (callback) callback(result);
}
});
}
And last c# generic method which checks returns model state errors
public static IEnumerable<object> GetModelErorrs(this ModelStateDictionary modelState)
{
return modelState.Keys.Where(x => modelState[x].Errors.Count > 0)
.Select(x => new {
key = x,
errors = modelState[x].Errors.Select(y => y.ErrorMessage).ToArray()
});
}
Hope answer is useful...

How to redirect an Ajax Method session on timeout

So I got a ajax method that returns a JSON result, but part of the method is to check if the session is valid.
So If a user refreshed a page, the ajax method is called, in which it throws an exception as the session has expired, now the method wants to return a JSON result, but instead I want to redirect them to the login page.
how do I do this?
public JsonResult GetClients()
{
var usertoken = new UserToken(this.User.Identity.Name);
if (usertoken.AccountId != null)
{
return new JsonResult() {Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
else
{
//Redirect Here
}
AFAIK you would only be able to do this via JavaScript since your call is using ajax, the solution to the other post would not work since the redirect header would not be honored for an ajax request.
You might want to add a status or hasExpire property to your return result:
[HttpPost]
public ActionResult GetClients()
{
var usertoken = new UserToken(this.User.Identity.Name);
if (usertoken.AccountId != null)
{
return Json(new { data = model, status = true });
}
else
{
return Json(new { data = null, status = false });
}
On your ajax call:
$.ajax('/controller/getclients', { }, function(data) {
if(data.status == true) {
// same as before you've got your model in data.data...
} else {
document.location.href = '/account/login';
}
});
Hope that help.
In Controller code, check for session validity. For example
if (Session["UserName"] == null)
{
return Json(new
{
redirectUrl = ConfigurationManager.AppSettings["logOffUrl"].ToString(),
isTimeout = true
});
}
In .js file check like the following
success: function (data) {
if (data != '' && typeof data != 'undefined') {
if (data.isTimeout) {
window.location.href = data.redirectUrl;
return;
}

ASP.NET MVC Ajax Error handling

How do I handle exceptions thrown in a controller when jquery ajax calls an action?
For example, I would like a global javascript code that gets executed on any kind of server exception during an ajax call which displays the exception message if in debug mode or just a normal error message.
On the client side, I will call a function on the ajax error.
On the server side, Do I need to write a custom actionfilter?
If the server sends some status code different than 200, the error callback is executed:
$.ajax({
url: '/foo',
success: function(result) {
alert('yeap');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
and to register a global error handler you could use the $.ajaxSetup() method:
$.ajaxSetup({
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
Another way is to use JSON. So you could write a custom action filter on the server which catches exception and transforms them into JSON response:
public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new { success = false, error = filterContext.Exception.ToString() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
and then decorate your controller action with this attribute:
[MyErrorHandler]
public ActionResult Foo(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new Exception("oh no");
}
return Json(new { success = true });
}
and finally invoke it:
$.getJSON('/home/foo', { id: null }, function (result) {
if (!result.success) {
alert(result.error);
} else {
// handle the success
}
});
After googling I write a simple Exception handing based on MVC Action Filter:
public class HandleExceptionAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
filterContext.Exception.Message,
filterContext.Exception.StackTrace
}
};
filterContext.ExceptionHandled = true;
}
else
{
base.OnException(filterContext);
}
}
}
and write in global.ascx:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleExceptionAttribute());
}
and then write this script on the layout or Master page:
<script type="text/javascript">
$(document).ajaxError(function (e, jqxhr, settings, exception) {
e.stopPropagation();
if (jqxhr != null)
alert(jqxhr.responseText);
});
</script>
Finally you should turn on custom error.
and then enjoy it :)
Unfortunately, neither of answers are good for me. Surprisingly the solution is much simpler. Return from controller:
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Response.ReasonPhrase);
And handle it as standard HTTP error on client as you like.
I did a quick solution because I was short of time and it worked ok. Although I think the better option is use an Exception Filter, maybe my solution can help in the case that a simple solution is needed.
I did the following. In the controller method I returned a JsonResult with a property "Success" inside the Data:
[HttpPut]
public JsonResult UpdateEmployeeConfig(EmployeConfig employeToSave)
{
if (!ModelState.IsValid)
{
return new JsonResult
{
Data = new { ErrorMessage = "Model is not valid", Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
try
{
MyDbContext db = new MyDbContext();
db.Entry(employeToSave).State = EntityState.Modified;
db.SaveChanges();
DTO.EmployeConfig user = (DTO.EmployeConfig)Session["EmployeLoggin"];
if (employeToSave.Id == user.Id)
{
user.Company = employeToSave.Company;
user.Language = employeToSave.Language;
user.Money = employeToSave.Money;
user.CostCenter = employeToSave.CostCenter;
Session["EmployeLoggin"] = user;
}
}
catch (Exception ex)
{
return new JsonResult
{
Data = new { ErrorMessage = ex.Message, Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
return new JsonResult() { Data = new { Success = true }, };
}
Later in the ajax call I just asked for this property to know if I had an exception:
$.ajax({
url: 'UpdateEmployeeConfig',
type: 'PUT',
data: JSON.stringify(EmployeConfig),
contentType: "application/json;charset=utf-8",
success: function (data) {
if (data.Success) {
//This is for the example. Please do something prettier for the user, :)
alert('All was really ok');
}
else {
alert('Oups.. we had errors: ' + data.ErrorMessage);
}
},
error: function (request, status, error) {
alert('oh, errors here. The call to the server is not working.')
}
});
Hope this helps. Happy code! :P
In agreement with aleho's response here's a complete example. It works like a charm and is super simple.
Controller code
[HttpGet]
public async Task<ActionResult> ChildItems()
{
var client = TranslationDataHttpClient.GetClient();
HttpResponseMessage response = await client.GetAsync("childItems);
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
List<WorkflowItem> parameters = JsonConvert.DeserializeObject<List<WorkflowItem>>(content);
return Json(content, JsonRequestBehavior.AllowGet);
}
else
{
return new HttpStatusCodeResult(response.StatusCode, response.ReasonPhrase);
}
}
}
Javascript code in the view
var url = '#Html.Raw(#Url.Action("ChildItems", "WorkflowItemModal")';
$.ajax({
type: "GET",
dataType: "json",
url: url,
contentType: "application/json; charset=utf-8",
success: function (data) {
// Do something with the returned data
},
error: function (xhr, status, error) {
// Handle the error.
}
});
Hope this helps someone else!
For handling errors from ajax calls on the client side, you assign a function to the error option of the ajax call.
To set a default globally, you can use the function described here:
http://api.jquery.com/jQuery.ajaxSetup.

Resources