You can create an action filter to override the layout file, but if you want to delete it, you will need to create an empty layout file instead of setting the Master property to null. Like this:
public class OverrideLayoutFilter : ActionFilterAttribute { public override void OnResultExecuting(ResultExecutingContext filterContext) { var view = filterContext.Result as ViewResult; view.MasterName = "_LayoutEmpty"; base.OnResultExecuting(filterContext); } }
Controller:
public class HomeController : Controller { [OverrideLayoutFilter] public ActionResult Index() { return View(); } }
Now your new layout file should be placed in the SharedFolder, and you only put the RenderBody function inside
_LayoutEmpty.cshtml
@RenderBody()
Note. If you have sections defined in the view that you want to override the layout, you will also need to define these sections with empty content.
source share