I have an ASP.NET MVC application with an Admin area that deals with administering Companies and their child entities, such as Users and Products. The default route associated with a child entity is defined as follows:
"Admin/Company/{companyID}/{controller}/{id}/{action}"
I would like to ensure that, everywhere in the Admin area, whenever the incoming route includes companyID, that this value is automatically included in every generated URL. For example, if my User Edi开发者_StackOverflowt page has a link defined with Html.ActionLink("back to list", "Index")
, the routing system will automatically grab the companyID from the incoming route data and include it in the outgoing route, without having to explicitly specify it in the call to ActionLink.
I think there's more than one way to achieve this, but is there a preferred/best way? Does it scream for a custom route handler? Something else?
My goal is to not lose the current company context when navigating around in the sub-sections, and I don't want to use Session - that could burn me if the user opens up multiple companies in different browser windows/tabs.
Thanks in advance!
Todd,
I am using an ActionFilterAttribute in my MVC 2 application to make this happen. There may be better ways to do this:
[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);
}
}
精彩评论