return Json will redirects to another view when Url specified

前端 未结 3 1886
礼貌的吻别
礼貌的吻别 2021-01-22 22:01

When you do return Json(...) you are specifically telling MVC not to use a view, and to serve serialized JSON data. Your browser opens a download dialog because it doesn\'t know

3条回答
  •  借酒劲吻你
    2021-01-22 22:32

    RedirectToAction simply returns 302 code to your browser with URL telling where the browser should redirect to. The browser immediately makes yet another call to the server to that URL obtained from redirection response.

    RedirectToAction internals are:

    1. Construct redirection url from parameters passed to RedirectToAction
    2. Return new RedirectToRouteResult
    3. In ExecuteResult of RedirectToRouteResult you can find the following line:

      context.HttpContext.Response.Redirect(destinationUrl, endResponse: false);

    which is merely returning 302 with redirection URL. More info - look at source code here.

    Returning JSON data simply returns JSON serialized object to your browser. Is not meant to do any redirect. To consume such a result you will likely call the server using $.ajax:

    $.ajax({
        url: 'sep/employee',
        type: 'POST'
        success: function(result) {
            // handle the result from the server, i.e. process returned JSON data
        }
    });
    

    ExecuteResult of JsonResult just serializes passed CLR object to the response stream, which lands in your browser after response is fully received. Then you can handle such response in JavaScript code.

    EDIT:

    You of course can mimic 302 redirection by returning Json like

    return Json(new { Url = "redirectionUrl"}
    

    and at client side handle it like

    $.ajax({
        url: 'sep/employee',
        type: 'POST'
        success: function(result) {
            // mimic the 302 redirection
            windows.location.href = result.Url
        }
    });
    

    although IMHO it should be avoided since you reinvent MVC infrastructure and enlarge your code base.

提交回复
热议问题