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 controller action doesn't specify the view name. When the view name isn't specified, the ViewResult returned by the action method applies a convention to locate the view. It first looks for a view with the same name as the action within the /Views/ControllerName directory (the controller name without the “Controller” suffix in this case). The view selected in this case would be /Views/Home/Index.cshtml.

As with most things in ASP.NET MVC, this convention can be overridden. Suppose that you want the Index action to render a different view. You could supply a different view name like so:

public ActionResult Index() {
    ViewBag.Message = "Welcome to ASP.NET MVC!";
    return View("NotIndex");
}

Code snippet 3-4.txt

In this case, it will still look in the /Views/Home directory, but choose NotIndex.cshtml as the view. In some situations, you might even want to specify a view in a completely different directory structure. You can use the tilde syntax to provide the full path to the view like so:

public ActionResult Index() {
    ViewBag.Message = "Welcome to ASP.NET MVC!";
    return View("∼/Views/Example/Index.cshtml");
}

Code snippet 3-5.txt

When using the tilde syntax, you must supply the file extension of the view because this bypasses the view engine's internal lookup mechanism for finding Views.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.133.54