"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Adding a View

by Scott Hanselman

This is a beginner tutorial that introduces the basics of ASP.NET MVC. You’ll create a simple web application that reads and writes from a database. Visit the ASP.NET MVC learning center to find other ASP.NET MVC tutorials and samples.

In this section we are going to look at how we can have our HelloWorldController class use a View template file to cleanly encapsulate generating HTML responses back to a client.

Let’s start by using a View template with our Index method. Our method is called Index and it’s in the HelloWorldController. Currently our Index() method returns a string with a message that is hardcoded within the Controller class.

[!code-csharpMain]

   1:  public string Index()
   2:  {
   3:      return "<html><body>This is my default action...</body></html>";
   4:  }

Let’s now change the Index method to instead look like this:

[!code-csharpMain]

   1:  public ActionResult Index()
   2:  {
   3:     return View(); 
   4:  }

Let’s now add a View template to our project that we can use for our Index() method. To do this, right-click with your mouse somewhere in the middle of the Index method and click Add View…

image
image

This will bring up the “Add View” dialog which provides us some options for how we want to create a view template that can be used by our Index method. For now, don’t change anything, and just click the Add button.

Add View Dialog

After you click Add, a new folder and a new file will appear in the Solution Folder, as seen here. I now have a HelloWorld folder under Views, and an Index.aspx file inside that folder.

solutionexplorerwithindex

The new Index file is also already opened and ready for editing. Add some text under the first <h2>Index</h2> like “Hello World.”

[!code-htmlMain]

   1:  <h2>Index</h2>
   2:  Hello world!

Run your application and visit http://localhost:xx/HelloWorld again in your browser. The Index method in our controller in this example didn’t do any work, but did call “return View()” which indicated that we wanted to use a view template file to render a response back to the client. Because we did not explicitly specify the name of the view template file to use, ASP.NET MVC defaulted to using the Index.aspx view file within the folder. Now we see the string we hard-coded in our View.

Index - Windows Internet Explorer

Looks pretty good. However, notice that the Browser’s title says “Index” and the big title on the page says “My MVC Application.” Let’s change those.

Changing Views and Master Pages

First, let’s change the text “My MVC Application.” That text is shared and appears on every page. It actually appears in only one place in our code, even though it’s on every page in our app. Go to the /Views/Shared folder in the Solution Explorer and open the Site.Master file. This file is called a Master Page and it’s the shared “shell” that all our other pages use.

Notice some text that says ContentPlaceholder “MainContent” in this file.

[!code-aspxMain]

   1:  <asp:ContentPlaceHolder ID="MainContent" runat="server" />

That placeholder is where all the pages you create will show up, “wrapped” in the master page. Try changing the title, then run your app and visit multiple pages. You’ll notice that your one change appears on multiple pages.

[!code-htmlMain]

   1:  <div id="title">
   2:      <h1>My MVC Movie Application</h1>
   3:  </div>

Now every page will have the Primary Heading - that’s H1 - of “My MVC Movie Application.” That handles the white text at the top there that’s shared across all the pages.

Here is the Site.Master in its entirety with our changed title:

[!code-aspxMain]

   1:  <%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
   2:   
   3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   4:  <html xmlns="http://www.w3.org/1999/xhtml">
   5:  <head runat="server">
   6:      <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
   7:      <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
   8:  </head>
   9:   
  10:  <body>
  11:      <div class="page">
  12:   
  13:          <div id="header">
  14:              <div id="title">
  15:                  <h1>My MVC Movie Application</h1>
  16:              </div>
  17:               
  18:              <div id="logindisplay">
  19:                  <% Html.RenderPartial("LogOnUserControl"); %>
  20:              </div>
  21:             
  22:              <div id="menucontainer">
  23:             
  24:                  <ul id="menu">             
  25:                      <li><%: Html.ActionLink("Home", "Index", "Home")%></li>
  26:                      <li><%: Html.ActionLink("About", "About", "Home")%></li>
  27:                  </ul>
  28:             
  29:              </div>
  30:          </div>
  31:   
  32:          <div id="main">
  33:              <asp:ContentPlaceHolder ID="MainContent" runat="server" />
  34:   
  35:              <div id="footer">
  36:              </div>
  37:          </div>
  38:      </div>
  39:  </body>
  40:  </html>

Now, let’s change the title of the Index page.

Open /HelloWorld/Index.aspx. There’s two places to change. First, the Title that appears in the title of the browser, then the secondary header - that’s H2 - as well. I’ll make them each slightly different so you can see which bit of code changes which part of the app.

[!code-aspxMain]

   1:  <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
   2:      Movie List
   3:  </asp:Content>
   4:   
   5:  <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
   6:   
   7:      <h2>My Movie List</h2>
   8:      Hello World!
   9:   
  10:  </asp:Content>

Run your app and visit /Movies. Notice that the browser title, the primary heading and the secondary headings have changed. It’s easy to make big changes in your app with small changes to your view.

Movie List - Windows Internet Explorer

Our little bit of “data” (in this case the “Hello World!” message) was hard coded though. We’ve got V (Views) and we’ve got C (Controllers), but no M (Model) yet. We’ll shortly walk through how create a database and retrieve model data from it.

Passing a ViewModel

Before we go to a database and talk about Models, though, let’s first talk about “ViewModels.” These are objects that represent what a View template requires to render an HTML response back to a client. They are typically created and passed by a Controller class to a View template, and should only contain the data that the View template requires - and no more.

Previously with our HelloWorld sample, our Welcome() action method took a name and a numTimes parameter and output it to the browser. Rather than have the Controller continue to render this response directly,let’s instead make a small class to hold that data and then pass it over to a View template to render back the HTML response using it. This way the Controller is concerned with one thing and the View template another – enabling us to maintain clean “separation of concerns” within our application.

Return to the HelloWorldController.cs file and add a new “WelcomeViewModel” class and change the Welcome method inside your controller. Here is the complete HelloWorldController.cs with the new class in the same file.

[!code-csharpMain]

   1:  using System.Web.Mvc;
   2:   
   3:  namespace Movies.Controllers
   4:  {
   5:      public class HelloWorldController : Controller
   6:      {
   7:          public ActionResult Index()
   8:          {
   9:              return View();
  10:          }
  11:   
  12:          public ActionResult Welcome(string name, int numTimes = 1)
  13:          {
  14:              var viewModel = new WelcomeViewModel
  15:              {
  16:                  Message = "Hello " + name,
  17:                  NumTimes = numTimes
  18:              };
  19:   
  20:              return View(viewModel);
  21:          }
  22:   
  23:          public class WelcomeViewModel
  24:          {
  25:              public string Message { get; set; }
  26:              public int NumTimes { get; set; }
  27:          }
  28:      }
  29:  }

Even though it’s on multiple lines, our Welcome method is really only two code statements. The first statement packages up our two parameters into a ViewModel object, and the second passes the resulting object onto the View.

Now we need a Welcome View template! Right click in the Welcome method and select Add View. This time, we’ll check “Create a strongly-typed view” and select our WelcomeViewModel class from the drop down list. This new view will only know about WelcomeViewModels and no other types of objects.

NOTE: You’ll need to have compiled once after adding your WelcomeViewModel for to show up in the drop down list.

Here’s what your Add View dialog should look like. Click the Add button. Add View circled

Add this code under the <h2> in your new Welcome.aspx. We’ll make a loop and say Hello as many times as the user says we should!

[!code-aspxMain]

   1:  <% for(int i=0;i<Model.NumTimes;i++) { %>
   2:         <%h3><%: Model.Message %></h3>
   3:  <% } %>

Also, notice while you’re typing that because we told this View about the WelcomeViewModel (they are married, remember?) that we get helpful Intellisense each time we reference our Model object as seen in the screenshot below:

NumTime Source Code

Run your application and visit http://localhost:xx/HelloWorld/Welcome?name=Scott&numtimes=4 again. Now we’re taking data from the URL, it’s passed into our Controller automatically, our Controller packages up the data into a ViewModel and passes that object onto our View. The View than displays the data as HTML to the user.

Welcome - Windows Internet Explorer

Well, that was a kind of an “M” for Model, but not the database kind. Let’s take what we’ve learned and create a database of Movies.

Previous Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/mvc/overview/older-versions-1/getting-started-with-mvc/getting-started-with-mvc-part3.htm
< THANKS ME>