Specifying a View

In the previous section, you looked at examples of what goes inside a view. In this section, you look at how to specify the view that should render the output for a specific action. It turns out that this is very easy when you follow the conventions implicit in the ASP.NET MVC Framework.

When you create a new project template, you'll notice that the project contains a Views directory structured in a very specific manner (see Figure 3.1).

By convention, the Views directory contains a folder per Controller, with the same name as the Controller, but without the Controller suffix. Thus for the HomeController, there's a folder in the views directory named Home.

Within each Controller folder, there's a view file for each action method, named the same as the action method. This provides the basis for how Views are associated to an action method.

For example, an action method can return a ViewResult via the View method like so:

UnFigure
public class HomeController : Controller {
    public ActionResult Index() {
        ViewBag.Message = "Welcome to ASP.NET MVC!";
        return View();
    }
}

Code snippet 3-3.txt

This method ought to look familiar; it's the Index action method of HomeController in the default project template.

Notice that unlike the sample in Code Snippet 3-3, this ...

Get Professional ASP.NET MVC 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.