0

How do you make a controller function that returns ResponseRedirect to instead return that ResponseRedirect as Json object?

I want to do something like this

 return Json(new { url = RedirectToAction("AccountMyProducts", "Account"), redirect = "true" });

To get the redirect url in my jsonobject.

tereško
  • 58,060
  • 25
  • 98
  • 150
user473104
  • 301
  • 2
  • 6
  • 17

2 Answers2

7

do like this

return Json(data, JsonRequestBehavior.AllowGet);

explanation : function returns the type of JsonResult, which is inherited by ActionResult.

  1. JsonRequestBehavior.AllowGet :
    From this Answer why-is-jsonrequestbehavior-needed

This is to protect against a very specific attack with JSON requests that return data using HTTP GET.

Basically, if your action method does not return sensitive data, then it should be safe to allow the get.

However, MVC puts this in with DenyGet as the default to protect you against this attack. It makes you consider the implications of what data you are exposing, before you decide to expose it over HTTP GET

if you are planning to redirect based on json data

return Json(new 
{ 
    redirectUrl = Url.Action("AccountMyProducts", "Account"), 
    isredirection= true 
});

in Jquery success call back function, do like this

$.ajax({
.... //some other stuffs including url, type, content type. 

//then for success function. 
success: function(json) {
    if (json.isredirection) {
        window.location.href = json.redirectUrl;
    }
}

});
Community
  • 1
  • 1
Ravi Gadag
  • 15,735
  • 5
  • 57
  • 83
0

You could try this:

return Json(new { url = "Account/AccountMyProducts", redirect = "true" });

It is worth noting that RedirectToAction(...) returns a RedirectToRouteResult which is evaluated by the method which calls your controller action, rather than returning the actual URL straight away.

rhughes
  • 9,257
  • 11
  • 59
  • 87