Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is is possible to specify searchable location formats for an MVC Razor Layout?

Tags:

asp.net-mvc

In Razor, when loading a partial view, it is possible to just specify the partial view name, and the Razor view engine will search the RazorViewEngine.PartialViewLocationFormats:

@Html.RenderPartial("_PartialView", Model);

will actually search the locations specified in PartialViewLocationFormats in the view engine, such as for example

~/Views/Home/_PartialView.cshtml
~/Views/Shared/_PartialView.cshtml

However, when specifying the Layout, I seem to be forced to specify a specific path to the layout:

@Layout = "~/Views/Shared/MyLayout.cshtml";

What I would like to do would be to specify the layout just by name, and have the the actual layout be found by searching a list of common locations:

@Layout = "MyLayout";

...but I can't find any facilities to do so. Since I could not find any documentation regarding this, I tried playing with setting RazorViewEngine.MasterLocationFormats, but this property is not used when locating layouts.

Does anybody know how to do this?

like image 535
Peter Spillman Avatar asked Mar 18 '11 19:03

Peter Spillman


People also ask

Which is a default view search path for the Razor view engine?

By default Razor Pages are stored in Pages folder under project root.

How do you use layout on razor page?

The Render body is used to inject razor page content in the layout view page. The Render section is used to inject content in the define section from the razor to the layout view. Multiple sections can be added from the razor page to the layout view. The render section is optional if not required.

What is razor view in MVC?

Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine. You can use it anywhere to generate output like HTML.


1 Answers

Recently I was struggling on a similar issue where, in a themed application that uses a custom ViewEngine to search theme's location first for views, I was trying to override some master files. One way to force the location of the layout to go through the ViewEngine's FindView is to specify the name of the master view in a controller action when returning:

return View("myView", "myViewMaster");

However, if "myViewMaster" also has a layout (nested layouts), this method doesn't work for the nested layout. My best solution so far is to call the view engine directly in the view:

@{
    Layout = (ViewEngines.Engines.FindView(this.ViewContext.Controller.ControllerContext, "myViewMaster", "").View as RazorView).ViewPath;
}

This works but could certainly be encapsulated in a extension method to avoid repetition and abstract the code.

Hope it helps!

like image 177
sowee15 Avatar answered Nov 09 '22 12:11

sowee15