Home >Backend Development >C++ >How Can I Customize View Locations in ASP.NET MVC to Find Views in Non-Standard Folders?

How Can I Customize View Locations in ASP.NET MVC to Find Views in Non-Standard Folders?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-26 00:51:10148browse

How Can I Customize View Locations in ASP.NET MVC to Find Views in Non-Standard Folders?

Finding views in non-standard folders: ASP.NET MVC view location customization

ASP.NET MVC searches for views at specific locations in the file system by default. However, customizing these search locations can be useful when projects are organized in a non-standard way. This article explores how to specify custom view positions.

Problem Overview

Suppose the project structure is as follows: the controller is located at /Controllers/Demo and the view is located at /Views/Demo. The following controller code may cause an error:

<code class="language-csharp">public class DemoArea1Controller : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}</code>

The default search location does not include the /Views/Demo folder, so an error will be reported, indicating that the view "Index" cannot be found.

Solution

To specify a custom view position, you can extend the WebFormViewEngine class and modify the PartialViewLocationFormats and ViewLocationFormats attributes:

<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/{1}/{0}.aspx",
            "~/Demo/Views/{1}/{0}.ascx"
        };

        this.PartialViewLocationFormats = viewLocations;
        this.ViewLocationFormats = viewLocations;
    }
}</code>

This updated view engine includes /Demo/Views folders in search locations.

Configuration

Finally, register the custom view engine in the Global.asax.cs method of Application_Start:

<code class="language-csharp">protected void Application_Start()
{
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new CustomViewEngine());
}</code>

With these modifications, ASP.NET MVC will now search for views in default locations and custom /Demo/Views folders.

The above is the detailed content of How Can I Customize View Locations in ASP.NET MVC to Find Views in Non-Standard Folders?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn