The Purpose of Views

Chapter 2 demonstrated how controllers can return strings, which are then output to the browser. That's useful for getting started with controllers, but in any non-trivial web application, you'll notice a pattern emerging very quickly: Most controller actions need to display dynamic information in HTML format. If the controller actions are just returning strings, they'll be doing a lot of string substitution, which gets messy fast. A templating system is clearly needed, which is where the view comes in.

The view is responsible for providing the user interface (UI) to the user. It is given a reference to the model (the information the controller needs displayed), and the view transforms that model into a format ready to be presented to the user. In ASP.NET MVC, the view accomplishes this by examining a model object handed off to it by the controller and transforming the contents of that to HTML.

Note
Not all views render HTML. HTML is certainly the most common case when building web applications. But, as the section on action results in Chapter 16 points out, views can render a wide variety of other content types as well.

Let's take a quick look at an example of a view. The following code sample shows a view named Sample.cshtml located at the path /Views/Home/Sample.cshtml. Don't worry about typing this; it's just for illustration.

Listing 3-1: Sample view — Sample.cshtml

@{ Layout = null; } <!DOCTYPE html> <html> <head><title>Sample View</title></head> ...

Get Professional ASP.NET MVC 4 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.