Customize view search position in ASP.NET MVC
When organizing an MVC project, it may be necessary to specify a custom location for view search operations. This allows the controller to look for views in specific subfolders to accommodate projects with unique directory structures.
Question:
In a project with the following layout:
<code>/Controllers /Demo /DemoArea1Controller /DemoArea2Controller 等等... /Views /Demo /DemoArea1/Index.aspx /DemoArea2/Index.aspx</code>
Use DemoArea1Controller with the following code:
<code>public ActionResult Index() { return View(); }</code>
will result in "View 'index' or its master page not found" error. By default, MVC searches for views in:
This problem occurs because the controller expects to find the Index.aspx view in ~/Views/DemoArea1, but the view is located in ~/Views/Demo/DemoArea1/Index.aspx.
Solution:
To specify a custom location for view search operations, extend the WebFormViewEngine class:
<code>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/{1}/{0}.aspx", "~/Demo/Views/{1}/{0}.ascx" }; this.PartialViewLocationFormats = viewLocations; this.ViewLocationFormats = viewLocations; } }</code>
In this extended engine, an additional search location ~/Demo/Views/{1}/{0}.aspx is added to the list of view locations. This allows controllers in the Demo namespace to look for views in the Demo views subfolder.
Remember to register your custom view engine in the Application_Start method of Global.asax.cs:
<code>protected void Application_Start() { ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new CustomViewEngine()); }</code>
By creating a custom view engine, developers can easily specify additional search locations for views, providing flexibility and organization in ASP.NET MVC projects.
The above is the detailed content of How Can I Customize View Search Locations in ASP.NET MVC to Find Views in Specific Subfolders?. For more information, please follow other related articles on the PHP Chinese website!