2010-07-08 33 views
2

我有一个ASP.NET MVC应用程序,其中包含一个处理管理公司及其子实体(例如用户和产品)的管理区域。与孩子实体相关联的默认路由定义如下:ASP.NET MVC路由 - 将入站路由值自动传递给出站URL?

"Admin/Company/{companyID}/{controller}/{id}/{action}" 

我想确保,无处不在的管理区,每当归路包括companyID,该值会自动包含在每个生成的URL 。例如,如果我的用户编辑页面有一个用Html.ActionLink("back to list", "Index")定义的链接,路由系统将自动从传入的路由数据中获取companyID,并将其包含在传出路由中,而不必在对ActionLink的调用中明确指定它。

我认为有多种方式可以实现这一目标,但是有没有一种首选/最佳方式?它是否为自定义路由处理程序而尖叫?还有别的吗?

我的目标是在小节中导航时不会丢失当前的公司上下文,而且我不想使用会话 - 如果用户在不同的浏览器窗口/选项卡中打开多个公司。

在此先感谢!

回答

0

托德,

我用我的MVC 2应用程序的ActionFilterAttribute做到这一点。可能有更好的方法来做到这一点:

[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method, Inherited = true, AllowMultiple = true)] 
sealed class MyContextProviderAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     // See if the context is provided so that you can cache it. 
     string myContextParam = filterContext.HttpContext.Request["myContextParam"] ; 
     if (!string.IsNullOrEmpty(myContextParam)) 
      filterContext.Controller.TempData["myContextParam"] = myContextParam; 
     else 
      // Manipulate the action parameters and use the cached value. 
      if (filterContext.ActionParameters.Keys.Contains("myContextParam")) 
       filterContext.ActionParameters["myContextParam"] = filterContext.Controller.TempData["myContextParam"]; 
      else 
       filterContext.ActionParameters.Add("myContextParam", filterContext.Controller.TempData["myContextParam"]); 

     base.OnActionExecuting(filterContext); 
    } 
} 
+0

感谢您的答复。有趣的解决方案。虽然我还没有尝试过,但TempData与会话绑定,因此我不认为这解决了我对用户在具有不同“上下文”的浏览器标签之间来回翻转的担忧。虽然我想避免编写一些其他UrlHelper方法(并记住始终使用它们),但这基本上是我最终采取的方式。 – 2011-05-21 13:47:07

+0

Todd,TempData只能存活后续请求,所以这应该适用于您。我的应用程序允许人们为不同标签中的不同人员提供报告。请参阅http://stackoverflow.com/questions/173159/difference-between-viewdata-and-tempdata – 2011-05-23 14:58:10