ASP.NET MVC View Search Location Customization Guide
In ASP.NET MVC projects, the default search location for views is the Views folder. However, you may encounter situations where you need to specify a custom location for a specific controller to find its corresponding view.
For example, suppose a controller under the "Demo" namespace needs to search for views in the "Demo" subfolder. The solution to this problem is to extend the default WebFormViewEngine and define a custom search location.
To do this, create a new class called CustomViewEngine, which inherits from WebFormViewEngine:
<code class="language-csharp">public class CustomViewEngine : WebFormViewEngine { public CustomViewEngine() { var viewLocations = new[] { "~/Views/{1}/{0}.aspx", "~/Views/{1}/{0}.ascx", "~/Views/Shared/{0}.aspx", "~/Views/Shared/{0}.ascx", "~/Demo/Views/{0}.ascx" }; this.PartialViewLocationFormats = viewLocations; this.ViewLocationFormats = viewLocations; } }</code>
In the constructor, define a custom search location. In this example, we add "~/Demo/Views/{0}.ascx" to the list of search locations, allowing controllers in the "Demo" namespace to be searched in the "Demo" subfolder.
Finally, register the custom view engine in the Application_Start method of the Global.asax.cs file:
<code class="language-csharp">protected void Application_Start() { ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new CustomViewEngine()); }</code>
Now when you use controllers in the "Demo" namespace, they will automatically search for views in the default Views folder and the "Demo" subfolder. This allows you to organize your view folders logically and maintain a consistent naming convention.
The above is the detailed content of How to Customize View Search Locations in ASP.NET MVC?. For more information, please follow other related articles on the PHP Chinese website!