Myślę, że można po prostu napisać ActionFilter jak ...
public class YourCustomLayoutAttribute : ActionFilterAttribute, IResultFilter
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
var viewResult = filterContext.Result as ViewResult;
if(viewResult != null)
{
// switch the layout
// I assume Razor will follow convention and take the "MasterName" property and change the layout based on that.
viewResult.MasterName = "CustomLayout";
}
}
}
Właśnie napisałem ten kod przez siedzibie spodnie bez kompilatora więc prawdopodobnie nie będzie kompilować ale prawdopodobnie się pomysł . Myślę, że IResultFilter jest właściwym interfejsem, który chcesz, ma metody, które są wykonywane tuż przed renderowaniem widoku. Jeśli jest to poprawne, powinieneś być w stanie zmodyfikować MasterName dla widoku, który ma być renderowany w locie.
To byłoby użycie kodu kontrolera.
[YourCustomLayout] // this should trigger your custom action result for all actions
public class MyController : Controller
{
public ActionResult Index()
{
return View("Index", "MainLayout"); // even if you were to use the overload to set a master, the action result should override it as it executes later in the pipeline.
}
}
Właściwie nie musisz dziedziczyć bezpośrednio z 'IResultFilter', ponieważ' ActionFilterAttribute' już to robi: 'public abstract class ActionFilterAttribute: FilterAttribute, IActionFilter, IResultFilter'. – Oliver