How to override view

Is there a way in asp.net MVC 3 to override the Layout declaration given in the view from a controller or action filter?

  @ {
     Layout = "~ / Views / Shared / _Layout.cshtml";
 } 

I tried to override the MasterName property in OnResultExecuted or OnResultExecuting, as the following code fragment, but to no avail.

  public override void OnResultExecuting (ResultExecutingContext filterContext)
 {
     var view = filterContext.Result as ViewResult;
     view.MasterName = null;
 } 
+4
source share
4 answers

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.

+3
source

Use the ViewBag when you need to change the layout invitation to an action and put a new layout (even null) in the viewbag.

 @{ Layout = ViewBag.layout; } 

and inside the action

 if(something) ViewBag.layout = "~/Views/Shared/whatever.cshtml"; else ViewBag.layout = null; 
+2
source

Another place where you can control the layout is in _ViewStart.cshtml .

Here you can make the necessary logic and programmatically indicate which layout to use. This allows you to place the logic in only one place and leave it out of sight.

 @{ if(myBusinessRule) { Layout = "~/Views/Shared/_Layout.cshtml"; } else { Layout = "~/Views/Shared/_SecondaryLayout.cshtml"; } } 

Blog post where it was submitted by Scott Gu

+2
source

Sorry, just add a link to one of my previous posts on this topic, but look here, this can give a broader review (pun intended) on the topic:

Where and how is the _ViewStart.cshtml layout file linked?

0
source

Source: https://habr.com/ru/post/1494119/


All Articles