2016-03-08 69 views
0

单击超链接时,我想在应用业务逻辑后导航到页面。目前,mvc动作中的“返回重定向(Url)”不会导航到该页面。MVC重定向不会导航到页面

$("a").bind("click", function (e) { 
     e.preventDefault(); 
     gotoUrl($, this.href); 
    }); 

gotoUrl: function ($, href) { 
    $.ajax({ 
      type: "POST", 
      url: 'mycontroller/myaction', 
      data: { url: href }, 
      dataType: 'json', 
      cache: false 
      success: function (data) { }   
     }); 
} 

//mycontroller 
[HttpPost] 
public ActionResult myaction(string url) 
{ 
    //Some business logic here to update url 
    return Redirect(url); 
} 

回答

0

为了改变当前窗口的位置,你需要检测你的Ajax请求被重定向(事后手动重定向),东西是不可能的,因为jQuery将跟随重定向。在类似的情况下,我实施了以下更通用的解决方法,但您可以根据需要进行调整。

在global.asax中为Application_EndRequest创建处理程序,拦截重定向响应并将响应代码重写为表示错误的其他东西,我使用代码422 - 不可处理的实体。

protected void Application_EndRequest() 
{ 
if (Context.Response.StatusCode == 302 && Context.Request.IsAjaxRequest()) 
{ 
    Context.Response.StatusCode = 422; 
} 
} 

在您的客户端脚本中,您现在需要通过添加通用ajax错误处理程序来检测这些422响应。

$(document) 
    .ajaxError(function (e, xhr, settings) { 
    if (xhr.status == 422) { 
    window.location = xhr.getResponseHeader('Location'); 
    } 
    })