When calling a function from ajax. Program flow does not recognized the expired session i.e not redirect to the login page. Instead of that, it saves the record. I am working in c# .net mvc. So how can i handle session while ajax call. Here i gave my codes.
$.ajax({
type: "POST",
url:'/Employee/SaveEmployee',
data:
{
Location:$("#txtLocation").val(),
dateApplied:$("#txtDateApplied").val(),
Status:$("#ddStatus").val(),
mailCheck:$("#ddMailCheck").val(),
...
...
...
},
success: function (result)
{
},
error: function (msg)
{
}
});
Here the controller
[Authorize]
public string SaveEmployee(string Location, string dateApplied, string Status, string mailCheck, ...)
{
objEmpMain.FirstName = firstName;
objEmpMain.LastName = lastName;
objEmpMain.Initial = Initial;
objEmpMain.Address1 = Address;
...
...
...
}
The result of your AJAX call will still likely end up appearing successful (although, don’t worry, it won’t actually execute your action method), and invoke your
successhandler. This is because you are expecting HTML, and that is what you are receiving (albeit, the resulting HTML is likely your login page, and not the HTML you wanted). As an aside, if you expected JSON (usingdataType:'JSON'), it would trigger an error, because it would be parsing HTML as JSON.What you need to do is prevent FormsAuth from redirecting the login page for AJAX requests. Now,
AuthorizeAttributefaithfully returns aNotAuthorizedResult, which sends an HTTP 401 Not Authorized response to the client, which is ideal for your AJAX client.The problem is that FormsAuth module checks the StatusCode and if it is 401, it performs the redirect. I’ve combatted this issue in this way:
1) Create my own derivative type of
AuthorizeAttributethat places a flag inHttpContext.Itemsto let me know authorization failed, and I should force a 401 rather than a redirect:2) Add to your Global.asax.cs:
3) Add a statusCode handler to your jQuery AJAX setup:
4) Change the controllers or actions where you want this behavior from using
AuthorizeAttributetoAjaxAuthorizeAttribute: