0

是否有人知道我如何使用asp.net mvc路由強制任何非ajax請求匹配控制器/動作/ ID總是迴應與主頁索引視圖?Asp.Net MVC路由的非xhr請求與Backbone.js

我正在開發一個Backbone.js applciation,並嘗試使用pushstate,因此我沒有hashfragment。我遇到的問題是書籤網址,如分頁網格/ CustomerDirectory/1響應與JSON - 我需要回應索引視圖,然後骨幹接管並啓動網格使用urland請求網格的JSON ?

回答

2

全局動作過濾器彈簧記:

public class MyFilter : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     if (!filterContext.HttpContext.Request.IsAjaxRequest()) 
     { 
      var rd = filterContext.RequestContext.RouteData; 
      var controller = rd.GetRequiredString("controller"); 
      var action = rd.GetRequiredString("action"); 
      var id = rd.Values["id"]; 
      if (DoYourTest()) 
      { 
       // Short-circuit the execution of the request action 
       // by setting the result which in this case will be 
       // a ViewResult to render the Home/Index view 
       filterContext.Result = new ViewResult 
       { 
        ViewName = "~/Views/Home/Index.cshtml" 
       }; 
      } 
     } 
    } 
} 

將在Global.asax註冊:

當然
public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
{ 
    filters.Add(new MyFilter()); 
    ... 
} 
+0

啊,過了一年,因爲我感動的MVC應用程序。讓我測試一下。乾杯 – redsquare

+0

工作過,感謝Darin。 – redsquare