0

I have a little app (asp.net mvc). I have a question: in my project i have a layout - _layout.chtml, It's possible to replace the content with different content that i inject from a file?

For example: Current _layout.chtml:

<!DOCTYPE html>
<html>
<head>
</head>
<body>      
    @RenderBody()
</body>
</html>

Now, i want to load new content from a file and replace the current _layout with new content as follows:

<!DOCTYPE html>
<html>
<head>
<title>My Title</title>
<link href="~/css/mycss.css" rel="stylesheet" />
</head>
<body>   
    @RenderPage("../Shared/_Header2.cshtml")    
    @RenderBody()
    @RenderPage("../Shared/_Footer2.cshtml")

    <script src="~/scripts/jquery.js"></script>
    <script src="~/scripts/angular.js"></script>
    @RenderSection("scripts", required: false)
</body>
</html>

How do i can to do that? Thanks!

David Michaeli
  • 367
  • 5
  • 26

2 Answers2

2

If you don't want overwrite your _ViewStart.cshtml you some other ways

return View ("NameOfView",masterName:"viewName");

Or store your layout in viewData like

//in controller
ViewData["Layout"]="your layout path";
//in _ViewStart.cshtml
Layout = ViewData["Layout"];

Or you can create a custom attribiute and set your layout name in it like

[LayoutInjecter("_PublicLayout")]
public ActionResult Index()
{
    return View();
}

for more information check this answer specify different Layouts

Community
  • 1
  • 1
M.Azad
  • 3,673
  • 8
  • 47
  • 77
1

I'll assume you're calling a new controller action at the time where you want to replace your layout. If so, then one of the following would do the trick;

First off you can put a _ViewStart.cshtml file in your \Views\ folder to override the default layout as seen below.

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

From here you can add another _ViewStart.cshtml file in \Views\User to override the default layout for all your \User\ views.

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

You can also specify the above in a view, e.g. for \Views\User\Index.cshtml.

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

Or you can specify the layout when returning the view in the controller;

return View("Index", "~/Views/Shared/_UserLayout.cshtml", someViewModel);
Rune Vikestad
  • 4,642
  • 1
  • 25
  • 36
  • thanks, but it is not help for me, it's not static layout, it can be replace sometimes, and i need to replace the content.. – David Michaeli Mar 09 '15 at 09:30
  • So you're trying to upload a new _Layout.cshtml file at runtime, and want the page to refresh using that layout instead of the site's default? The solution I provided is not just for static content, but it would require a set of predefined layouts. – Rune Vikestad Mar 09 '15 at 09:38