I would like to have 2 separate Layouts in my application. Let say one is for the Public section of the website and the other is empty for some reasons we need.
Before Core I could do this to define a filter:
public class LayoutInjecterAttribute : ActionFilterAttribute { private readonly string _masterName; public LayoutInjecterAttribute(string masterName) { _masterName = masterName; } public override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); var result = filterContext.Result as ViewResult; if (result != null) { result.MasterName = _masterName; } }
}
Now the ViewResult do not have the MasterName property. Is it possible to do now, and not to use in the View the layout definition.
Yes, we can use multiple Layout in ASP.Net MVC application. By default, Visual Studio adds a Layout page in a shared folder which can be used by other View pages if required. In some cases, we can have the requirement to use multiple shared layout pages in MVC application.
Razor has a feature called "layouts" that allow you to define a common site template, and then inherit its look and feel across all the views/pages on your web application.
You can still do something very similar to your original approach, using ViewData
to pass around the layout name (Although I would create it as a Result Filter):
public class ViewLayoutAttribute : ResultFilterAttribute { private string layout; public ViewLayoutAttribute(string layout) { this.layout = layout; } public override void OnResultExecuting(ResultExecutingContext context) { var viewResult = context.Result as ViewResult; if (viewResult != null) { viewResult.ViewData["Layout"] = this.layout; } } }
Then in the _ViewStart.cshtml
file:
@{ Layout = (string)ViewData["Layout"] ?? "_Layout"; }
Finally, assuming you create a new layout like Views/Shared/_CleanLayout.cshtml
, you can use that attribute on any controller or action:
[ViewLayout("_CleanLayout")] public IActionResult About() { //... }
This is how I am using multiple layouts in my ASP.NET core MVC application.
You can try like this-
In _ViewStart.cshtml
specify default _Layout like this-
@{ Layout = "_Layout"; }
If you want to set page specific layout then in that page.cshtml
, you can assign other view like this-
@{ Layout = "~/Views/Shared/_Layout_2.cshtml"; ViewData["Title"] = "Page Title"; }
See if this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With