C# - Changing Window Address when making an AJAX Call

96 views Asked by At

I have a C# page that checks that a user is logged in when making ajax calls and regular calls. I run the following check after determining the user is not logged in:

base.OnActionExecuting(filterContext);
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
  return Content("<script type='text/javascript'> window.location = '/login' </script>");
}
else
{
  filterContext.Result = new RedirectResult("~/Login/?referURL=" + filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.PathAndQuery));
}

The problem I am running into is in the 'if' part. I get an error saying that the name 'Content' does not exist. I need a way to redirect my window location to '/login'.

1

There are 1 answers

2
gunvant.k On

Instead of returning plain text return Json data and grab your redirect url from there and set redirect on Ajax success.

 var data = new { IsSucess = true, 
                  redirectUrl = Url.Action("Action", "Controller")}

filterContext.Result = new JsonResult() { data  , 
                       JsonRequestBehavior = JsonRequestBehavior.AllowGet };

Then use JsonResult data like this in your Ajax call,

success: function (data) {
                if (data.IsSucess)
                    window.location = data.redirectUrl;