KeelRisk
KeelRisk

Reputation: 749

RedirectToAction not redirecting

It starts here in the .ascx on a button click.

<script type="text/javascript">

function acceptG(id) {
    jQuery.get('<%: Url.Action("Accept", "Gift") %>', { id: id });
}

</script>

Then, here is the Controller is where the RedirectToAction is:

 [Authorize]
    public ActionResult Accept(long id)
    {
        var result = _gtService.AcceptG(id, User.UserID);
        if (result.Success)
            return RedirectToAction("Index", "Magnets");
        else 
        return View("InvalidG");             
    }

Here is the Index

 public ActionResult Index()
    {
        ViewData["Count"] = _souvenirService.GetDataForUser(User.UserID).Count();
        return View();
    }

One thing to remember is when using the Menu and hitting this Index the page comes up successfully, so it does work. But when using the RedirectToAction it hits all the code but does not redirect. Any help is appreciated.

Upvotes: 1

Views: 1833

Answers (1)

Praveen Prasad
Praveen Prasad

Reputation: 32107

Jquery is not magic, its just a wrapper for javascript. When you do a redirect on server that doesn't mean that your browser(ajax-request) will automatically understand what you mean to do. You have to tell browser that we want to redirect. I have created very tiny system for your need , but you can create complex one-as per your applications requirement.

<script type="text/javascript">

function acceptG(id) {
    jQuery.ajax({
          url:'<%: Url.Action("Accept", "Gift") %>',
          data:{ id: id },
          success:function(data)
          {
               if(data=='Redirect') 
               {
                    window.location='<%: Url.Action("Index", "Magnets") %>';
               }
               else
               {
                   //do something else
               }
          }
     });
}

</script>



 [Authorize]
    public ActionResult Accept(long id)
    {
        var result = _gtService.AcceptG(id, User.UserID);
        if (result.Success)
            if(Request.IsAjaxRequest())
            {
                  return Content('Redirect')
            }
            return RedirectToAction("Index", "Magnets");
        else 
        return View("InvalidG");             
    }

Upvotes: 3

Related Questions