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

江枫思渺然 提交于 2019-11-29 21:28:10

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.

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.

64X0P

What to do you think about trying to call:

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

instead of using redirects?

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;
                           }
                        },

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!