How to redirect to a controller action from a JSONResult method in ASP.NET MVC?
Asked Answered
M

5

25

I am fetching records for a user based on his UserId as a JsonResult...

public JsonResult GetClients(int currentPage, int pageSize)
{
   if (Session["UserId"] != "")
   {
      var clients = clirep.FindAllClients().AsQueryable();
      var count = clients.Count();
      var results = new PagedList<ClientBO>(clients, currentPage - 1, pageSize);
      var genericResult = new { Count = count, Results = results };
      return Json(genericResult);
   }
   else
   {
         //return RedirectToAction("Index","Home");
   }
}

How to redirect to a controller action from a JsonResult method in asp.net mvc?Any suggestion...

EDIT: This doesn't seem to work...

if (Session["UserId"] != "")
            {
                var clients = clirep.FindAllClients().AsQueryable();
                var count = clients.Count();
                var results = new PagedList<ClientBO>(clients, currentPage - 1, pageSize);
                var genericResult = new { Count = count, Results = results ,isRedirect=false};
                return Json(genericResult);
            }
            else
            {
                return Json({redirectUrl = Url.Action("Index", "Home"), isRedirect = true });
            }
Maracanda answered 19/5, 2010 at 11:20 Comment(0)
L
63

This will depend on how you are invoking this controller action. As you are using JSON I suppose that you are calling it in AJAX. If this is the case you cannot redirect from the controller action. You will need to do this in the success callback of the AJAX script. One way to achieve it is the following:

return Json(new 
{ 
    redirectUrl = Url.Action("Index", "Home"), 
    isRedirect = true 
});

And in the success callback:

success: function(json) {
    if (json.isRedirect) {
        window.location.href = json.redirectUrl;
    }
}

Remark: Make sure to include isRedirect = false in the JSON in case you don't want to redirect which is the first case in your controller action.

Leopard answered 19/5, 2010 at 11:24 Comment(2)
I redirect with AJAX all the time, but when using posted form field collections, not when using JSON. In fact, I'm trying to track down a bug involving redirection with JSON-posted data right now: #4111389 It sounds like this isn't something I can do then, yeah?Economic
Hi Darin, Thanks for your response, already voted you on this. My message may be after too long but wanted to know is there any way that in success condition, redirect should taken care by MVC controller and not from UI.Antonomasia
T
4

Adding to Darin Dimitrov's answer. For C#.NET MVC - If you want to redirect to a different page/controller and want to send an Object/Model to the new controller, You can do something like this.

In the JsonResult Method (in the controller):

 ErrorModel e = new ErrorModel();
            e.ErrorTitle = "Error";
            e.ErrorHeading = "Oops ! Something went wrong.";
            e.ErrorMessage = "Unable to open Something";



return Json(new 
{ 
    redirectUrl = Url.Action("Index", "Home",e), 
    isRedirect = true 
});

And in the success callback:

success: function(json) {
    if (json.isRedirect) {
        window.location.href = json.redirectUrl;
    }
}

And if the new controller can accept the model/object like below.. you can pass the object to the new controller/page

    public ActionResult Index(ErrorModel e)
    {
        return View(e);
    }

Hope this helps.

Teston answered 2/5, 2013 at 20:59 Comment(0)
F
2

What to do you think about trying to call:

return (new YourOtherController()).JSONResultAction();

instead of using redirects?

Fellows answered 27/9, 2011 at 8:2 Comment(0)
N
1

And if you work with areas ...

Controller:

return Json(new
        {
            redirectUrl = Url.Action("Index", "/DisparadorProgSaude/", new { area = "AreaComum" }),
            isRedirect = true
        });

View:

success: function (json) {

                           if (json.isRedirect) {
                           window.location.href = json.redirectUrl;
                           }
                        },
Numidia answered 8/11, 2016 at 16:43 Comment(0)
S
0

No way to do this, the client is executing an AJAX script so will not be able to handle anything else.

I suggest you redirect in the client script based on the returned data in the callback function.

Take a look at a similar question here: http://bytes.com/topic/javascript/answers/533023-ajax-redirect

Soleure answered 19/5, 2010 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.