I'm building an asp.net mvc2 website and using a lot of ajax form elementes (Ajax.BeginForm to be exact) to asynchronously populate data on the page. I would like to redirect the user to the sign in page after x amount of time of inactivity on the site. When I do this currently, either through ActionExecutingContext, or HttpContext, the sign in page is populated in the current div element for that ajax form, instead of the entire page. Any thoughts on how to get it to redirect the current page?
If you want to redirect the user to another page (login page) when the form is submitted then why use ajax ? AJAX is best used for the manipulation of a part of the page not and the whole page.
The Ajax.BeginForm has an option object to specify the id of the HTML element to be updated and the type of the update
example
Ajax.BeginForm("Create", "Project",
new AjaxOptions() {
UpdateTargetId = "projectform",
InsertionMode = InsertionMode.Replace,
HttpMethod = "Post" })
The InsertionMode option has three values Replace
, InsertAfter
, InsertBefore
In your case i don't know if you can target the HTML tag in the UpdateTargetId. but as i said earlier it's better to use a normal request in this scenario and not to update the whole page using Ajax.
about redirecting the user to the sign in page after a time of inactivity. I believe Sessions is the right way to do that. I'm not sure though how it's done.
Update :
i hope this link will help : http://blog.tallan.com/2010/06/25/handle-asp-net-mvc-session-expiration/
Solution:
override the OnActionExecuted event in your base controller, and create a RedirectResult to call into for wherever you want to redirect. Add the following code:
protected RedirectResult Redirect(string url, ActionExecutedContext filterContext)
{
return new AjaxErrorRedirectResult(url, filterContext);
}
public class AjaxErrorRedirectResult : RedirectResult
{
public AjaxErrorRedirectResult(string url, ActionExecutedContext filterContext)
: base(url)
{
ExecuteResult(filterContext.Controller.ControllerContext);
}
public override void ExecuteResult(ControllerContext context)
{
if (context.RequestContext.HttpContext.Request.IsAjaxRequest())
{
string redirectUrl = "www.google.com";
JavaScriptResult result = new JavaScriptResult()
{
Script = "self.parent.location='" + redirectUrl + "';"
};
result.ExecuteResult(context);
}
else
{
base.ExecuteResult(context);
}
}
}