1

So I have a table in my view and with the help of the following script I send the ajax data to the controller which updates my database:

$('.save-table').on('click', function () {
                var tr = $(this).parents('tr:first');
                var PredefName = tr.find("#PredefName").val();
                var PredefDescription = tr.find("#PredefDescription").val();
                var PredefID = tr.find("#PredefID").html();
                tr.find("#lblPredefName").text(PredefName);
                tr.find("#lblPredefDescription").text(PredefDescription);
                tr.find('.edit-mode, .display-mode').toggle();

                $.ajax({
                    url: '/PredefinedViews/Update/',
                    data: JSON.stringify({ pID: PredefID, pName: PredefName, pDescript: PredefDescription }),
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    error: function (event, jqxhr, settings, exception) {
                        alert("something went wrong")
                        if (jqxhr.status == 401) {
                            alert("session expired!");
                        }
                    },
                    success: function (event, jqxhr, settings, exception) {
                        alert("database updated!");
                    }
                });
            });

So I have a session that needs to be 5mins short which I set up successfully, I need the user to be notified that the session has expired BUT the error message never triggers after session has expired! it does however ALWAYS trigger the success message even if nothing has been saved to the database. So my question is, how do I trigger the ajax error?

EDIT1 Here is the method in my controller:

        [HttpPost]
    [ValidateInput(false)]
    public ActionResult Update(int pID, string pName, string pDescript)
    {
        using (PanSenseEntities context = new PanSenseEntities())
        {
            tblPredefineView existingPredefineView = context.tblPredefineViews.Find(pID);
            existingPredefineView.Name = pName;

            existingPredefineView.Description = pDescript;
            context.SaveChanges();
        }
        return Json(JsonRequestBehavior.AllowGet);
    }

EDIT2 I just realized that if the session expires it doesn't even reach the controller! Im stumped here now...

Vrankela
  • 1,162
  • 3
  • 16
  • 39

4 Answers4

1

Here is a similar question

Code from there, @Darin Dimitrov suggest to create custom authorize attribute and handle unauthorized requests:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.Result = new JsonResult
            {
                Data = new 
                { 
                    // put whatever data you want which will be sent
                    // to the client
                    message = "sorry, but you were logged out" 
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}
Community
  • 1
  • 1
aleha_84
  • 8,309
  • 2
  • 38
  • 46
1

On the server side, check for session expired or not, if it expired then throw an error with status code 401 as below.

throw new HttpException(401, "Unauthorized access");
Venkatesh
  • 1,204
  • 1
  • 10
  • 18
0

Write your server code in try-catch block, and throw the exception in catch block. It will surely trigger ajax error. Note that the error callback will be executed when the response from the server is not going to be what you were expecting. As long as there is correct response from server, ajax-error will not be triggered.

Saket Kumar
  • 4,363
  • 4
  • 32
  • 55
0

You need to check the session, something like :

[HttpPost]
[ValidateInput(false)]
public ActionResult Update(int pID, string pName, string pDescript)
{
    if(!HttpContext.Current.User.Identity.IsAuthenticated)
    {
       throw new HttpException(401, "Unauthorized access");
    }

    using (PanSenseEntities context = new PanSenseEntities())
    {
        tblPredefineView existingPredefineView = context.tblPredefineViews.Find(pID);
        existingPredefineView.Name = pName;

        existingPredefineView.Description = pDescript;
        context.SaveChanges();
    }
    return Json(JsonRequestBehavior.AllowGet);
}

Here, I check the session with :

HttpContext.Current.User.Identity.IsAuthenticated

And then, the error bloc in your request will be executed if HttpContext.Current.User.Identity.IsAuthenticated == false.

Vinc 웃
  • 1,187
  • 4
  • 25
  • 64
  • The problem is that the breakpoint doesnt even hit the controller if the session expired. It only gets there while session exists – Vrankela Dec 18 '14 at 13:59