使用Backbone.js的非xhr请求的Asp.Net MVC路由

时间:2012-01-20 18:25:29

标签: asp.net-mvc asp.net-mvc-3 backbone.js asp.net-mvc-routing

有人知道我如何使用asp.net mvc路由强制任何非ajax请求匹配controller / action / id总是以home索引视图响应吗?

我正在开发Backbone.js应用程序并尝试使用pushstate因此我没有hashfragment。我遇到的问题是带有书签的网址,例如分页网格/ CustomerDirectory / 1使用json进行响应 - 我需要使用索引视图进行响应,然后主干接管并使用urland请求启动网格网格的json?

1 个答案:

答案 0 :(得分: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());
    ...
}