user20358
user20358

Reputation: 14756

Asp.Net MVC Controllers - Action and Views mapping metadata

In my ASP.net MVC application, running off the ASPX view engine, I have a controller that has multiple action methods. To each of these action methods, I have noticed I can assign multiple views and then call each by name in the controller's action method.

I'd like to know where this mapping data is stored in the project. I scanned the project files and found this information to be nowhere. How does one know in large projects containing multiple views where to find all the views for a particular action. I initially thought this would be stored in some config file generated and maintained by Visual Studio. But that doesn't seem to be the case. So where is this data stored then? It will be a nightmare to figure out which files are really required and which are not, in large projects having multiple views.

What are your thoughts on this?

Upvotes: 3

Views: 3767

Answers (2)

Lester
Lester

Reputation: 4413

Santiago is correct that ASP.NET MVC is heavily convention based, but to expand on it more, when a controller looks like this:

public class FooController : Controller
{
    public ActionResult Bar()
    {
        return View();
    }
}

By convention, the view engine will search for a view called Bar under the following locations:

~/Views/Foo
~/Views/Shared

This is easily seen by adding a new action and not adding the view, you'll get this informative exception screen:

The view 'Bar' or its master was not found or no view engine supports the searched 
locations. The following locations were searched:
    ~/Views/Foo/Bar.aspx
    ~/Views/Foo/Bar.ascx
    ~/Views/Shared/Bar.aspx
    ~/Views/Shared/Bar.ascx
    ~/Views/Foo/Bar.cshtml
    ~/Views/Foo/Bar.vbhtml
    ~/Views/Shared/Bar.cshtml
    ~/Views/Shared/Bar.vbhtml

Likewise, if you have return View("ViewNameHere") it will look for ViewNameHere under the same locations.

To answer your question, even though a project may have hundreds of views and actions can return multiple views, unless you override the behavior of the view engine, all views are grouped according to their controller or placed in the shared folder.

Upvotes: 4

santiagoIT
santiagoIT

Reputation: 9431

asp.net mvc is heavily convention based. The view returned by the controller is implied by the method name unless no explicit view name is used. For further info check-out: asp-net-mvc-views-overview-cs

Upvotes: 3

Related Questions