Reputation: 2339
I have a method that is called by an ajax request. Implemented a SessionExpireFilter
inherited by ActionFilterAttribute
. I want to redirect to another action on failed condition in SesssionExpireFilter. My code is as below.
Method
[HttpPost]
[SessionExpireFilter]
public string SaveInstitute(int id, string category, string institute)
{
return DBMethodWeb.SaveInstitute(id, Convert.ToInt32(category), institute);
}
SessionExpireFilter
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
if (HttpContext.Current.Session[SessionManagement.SchoolId] != null)
{
}
else
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "Index" }));
// HttpContext.Current.Response.Redirect(@"~/Home/Index");
}
base.OnActionExecuting(filterContext);
}
Its rendering the page in ajax response. I want to redirect to an action.
Upvotes: 0
Views: 2868
Reputation: 17182
Instead of redirecting at the server side, you can redirect on the client side as shown below -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script>
function callme(data) {
window.location.href = data;
}
</script>
@using (Ajax.BeginForm("YourActionName", new AjaxOptions { OnSuccess = "callme" }))
{
<div>
<input type="submit" value="Click me" />
</div>
}
You ActionFilter should return a JsonResult as shown below -
public class SessionExpireFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Result = new JsonResult() { Data = "http://www.google.com", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
base.OnActionExecuting(filterContext);
}
}
For testing purpose, I used following action -
[SessionExpireFilter]
public ActionResult YourActionName()
{
return View();
}
At the end, my page got successfully redirected.
NOTE: The same example will work even if we make a JQuery AJAX request through code instead of AJAX form. All we need to do is to handle Success Function.
Upvotes: 1
Reputation: 4753
Can you try this:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
if (HttpContext.Current.Session[SessionManagement.SchoolId] != null)
{
}
else
{
filterContext.Result = new ViewResult
{
ViewName = "you path for particular view"
};
}
base.OnActionExecuting(filterContext);
}
Hope this helps..
Upvotes: 0