Well we’ve arrived at the last part of our series on ASP.NET MVC. In this post we’ll be looking at Views, ViewData, and HTML Helpers. We’ll be discussing how to call Views from Controllers and how to use HTML Helpers to create your markup.

Views In A Nutshell

Suppose we receive the following request; http://yourdomain.com/Task/Show/23. The request would map to the following controller.

1:publicclass TaskController : Controller

2: {

3:public ActionResult Show()

4: {

5:return View();

6: }

7: }

The call to View() will return a view to be displayed. This view is located YourProject\Views\Task\Index.aspx. If the view were called like View("TaskDetail") then it would use the view at YourProject\Views\Task\TaskDetail.aspx. That is all there is to calling a view from a controller.

The View Content

Calling the view is the easy part but we still need to pass data to our view and build the HTML to display the content. Here is a basic shell for a view page

There is nothing new here except your page declaration inherits from the ViewPage class. The rest is just standard HTML markup. So what can we put in the view for content? Well, you can input code snippets using server tags just like you can in WebForms.

Hello World, it is

Again this is nothing really new. MVC introduces HTML Helpers that take the place of Server Controls and help you build out your HTML. For example lets create a link to another section of our application.

Please click to view the employee list.

What this does is create the anchor markup for us and takes care of setting the href attribute properly based on the Routes we have defined for our application.

Passing Data From The Controller To The View

Now that you know how to create a view you will need to pass data from your controllers to your views. This is done very easily but adding your data to a key/value collection in the controller. public