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

Introducing ASP.NET Web Pages - Creating a Consistent Layout

by Tom FitzMacken

This tutorial shows you how to use layouts to create a consistent look for the pages on a site that uses ASP.NET Web Pages. It assumes you have completed the series through Deleting Database Data in ASP.NET Web Pages.

What you’ll learn:

  • What a layout page is.
  • How to combine layout pages with dynamic content.
  • How to pass values to a layout page.

About Layouts

The pages you’ve created so far have all been complete, standalone pages. They all belong to the same site, but they don’t have any common elements or a standard look.

Most sites do have a consistent look and layout. For example, if you go to the Microsoft.com/web site and look around, you see that the pages all adhere to an overall layout and to a visual theme:

Microsoft.com/web site page showing the layout of the header, navigation area, content area, and footer
Microsoft.com/web site page showing the layout of the header, navigation area, content area, and footer

An inefficient way to create this layout would be to define a header, navigation bar, and footer separately on each of your pages. You’d be duplicating the same markup each time. If you wanted to change something (for example, update the footer), you’d have to change each page separately.

That’s where layout pages come in. In ASP.NET Web Pages, you can define a layout page that provides an overall container for pages on your site. For example, the layout page can contain the header, navigation area, and footer. The layout page includes a placeholder where the main content goes.

You can then define individual content pages that contain the markup and the code for only that page. Content pages don’t have to be complete HTML pages; they don’t even have to have a <body> element. They also have a line of code that tells ASP.NET what layout page you want to display the content in. Here’s a picture that shows roughly how this relationship works:

Conceptual diagram that shows two content pages and a layout page into which they fit
Conceptual diagram that shows two content pages and a layout page into which they fit

This interaction is easy to understand when you see it in action. In this tutorial, you’ll change your movies pages to use a layout.

Adding a Layout Page

You’ll start by creating a layout page that defines a typical page layout with a header, footer, and an area for the main content. In the WebPagesMovies site, add a CSHTML page named _Layout.cshtml.

The leading underscore ( _ ) character is significant. If a page’s name starts with an underscore, ASP.NET won’t directly send that page to the browser. This convention lets you define pages that are required for your site but that users shouldn’t be able to request directly.

Replace the content in the page with the following:

[!code-htmlMain]

   1:  <!DOCTYPE html>
   2:  <html>
   3:    <head>
   4:      <title>My Movie Site</title>
   5:      <link href="~/Styles/Movies.css" rel="stylesheet" type="text/css" />
   6:    </head>
   7:    <body>
   8:      <div id="container">
   9:          <div id="header">
  10:            <h1>My Movie Site</h1>
  11:          </div>
  12:          <div id="main">
  13:            @RenderBody()
  14:          </div>
  15:          <div id="footer">
  16:            &copy; @DateTime.Now.Year My Movie Site
  17:          </div>
  18:      </div>
  19:    </body>
  20:  </html>

As you can see, this markup is just HTML that uses <div> elements to define three sections in the page plus one more <div> element to hold the three sections. The footer contains a bit of Razor code: @DateTime.Now.Year, which will render the current year at that location in the page.

Notice that there’s a link to a style sheet named Movies.css. The style sheet is where the details of the physical layout of the elements will be defined. You’ll create that in a moment.

The only unusual feature in this _Layout.cshtml page is the @Render.Body() line. That’s the placeholder where the content will go when this layout is merged with another page.

Adding a .css File

The preferred way to define the actual arrangement (that is, appearance) of elements on the page is to use cascading style sheet (CSS) rules. So you’ll create a .css file that has the rules for your new layout.

In WebMatrix, select the root of your site. Then in the Files tab of the ribbon, click the arrow under the New button and then click New Folder.

The ‘New Folder’ option under New in the ribbon.
The ‘New Folder’ option under New in the ribbon.

Name the new folder Styles.

Naming the new folder ‘Styles’
Naming the new folder ‘Styles’

Inside the new Styles folder, create a file named Movies.css.

Creating a new Movies.css file
Creating a new Movies.css file

Replace the contents of the new .css file with the following:

[!code-cssMain]

   1:  html{ height:100%; margin:0; padding:0; }
   2:   
   3:  body {
   4:    height:60%;
   5:    font-family:'Trebuchet MS',  'Arial', 'Helvetica', 'sans-serif';
   6:    font-size:10pt;
   7:    background-color: LightGray;
   8:    line-height:1.6em;
   9:  }
  10:   
  11:  h1{ font-size:1.6em; }
  12:  h2{ font-size:1.4em; }
  13:   
  14:  #container{
  15:     min-height:100%;
  16:     position:relative;
  17:     left:10%;
  18:  }
  19:   
  20:  #header{
  21:    padding:8px;
  22:    width:80%;
  23:    background-color:#4b6c9e;
  24:    color:White;
  25:  }
  26:   
  27:  #main{
  28:    width:80%;
  29:    padding: 8px;
  30:    padding-bottom:4em;
  31:    background-color:White;
  32:  }
  33:   
  34:  #footer{
  35:    width:80%;
  36:    height:2em;
  37:    padding:8px;
  38:    margin-top:-2em;
  39:    background-color:LightGray;
  40:  }
  41:   
  42:  .head { background-color: #E8E8E8; font-weight: bold; color: #FFF; }
  43:  .grid th, .grid td { border: 1px solid #C0C0C0; padding: 5px; }
  44:  .alt { background-color: #E8E8E8; color: #000; }
  45:  .selected {background-color:Yellow;}
  46:  span.caption {width:100px;}
  47:  span.dataDisplay {font-weight:bold;}

We won’t say much about these CSS rules, except to note two things. One is that in addition to setting fonts and sizes, the rules use absolute positioning to establish the location of the header, footer, and main content area. If you’re new to positioning in CSS, you can read the CSS Positioning tutorial at the W3Schools site.

The other thing to note is that at the bottom, we’ve copied the style rules that were originally defined individually in the Movies.cshtml file. These rules were used in the Introduction to Displaying Data by Using ASP.NET Web Pages tutorial to make the WebGrid helper render markup that added stripes to the table. (If you’re going to use a .css file for style definitions, you might as well put the style rules for the whole site in it.)

Updating the Movies File to Use the Layout

Now you can update the existing files in your site to use the new layout. Open the Movies.cshtml file. At the top, as the first line of code, add the following:

[!code-csharpMain]

   1:  Layout = "~/_Layout.cshtml";

The page now starts out this way:

[!code-cshtmlMain]

   1:  @{
   2:      Layout = "~/_Layout.cshtml";
   3:   
   4:      var db = Database.Open("WebPagesMovies") ;
   5:      var selectCommand = "SELECT * FROM Movies";
   6:      var searchTerm = "";
   7:   
   8:      // Etc.

This one line of code tells ASP.NET that when the Movies page runs, it should be merged with the _Layout.cshtml file.

Since the Movies.cshtml file now uses a layout page, you can remove the markup from the Movies.cshtml page that’s taken care of by the _Layout.cshtml file. Take out the <!DOCTYPE>, <html>, and <body> opening and closing tags. Take out the entire <head> element and its contents, which includes the style rules for the grid, since you’ve now got those rules in a .css file. While you’re at it, change the existing <h1> element to an <h2> element; you have an <h1> element in the layout page already. Change the <h2> text to “List Movies”.

Normally you wouldn’t have to make these sorts of changes in a content page. When you start your site out with a layout page, you create content pages without all these elements to begin with. In this case, though, you’re converting a standalone page to one that uses a layout, so there’s a bit of cleanup.

When you’re finished, the Movies.cshtml page will look like the following:

[!code-cshtmlMain]

   1:  @{
   2:      Layout = "~/_Layout.cshtml";
   3:   
   4:      var db = Database.Open("WebPagesMovies") ;
   5:      var selectCommand = "SELECT * FROM Movies";
   6:      var searchTerm = "";
   7:   
   8:      if(!Request.QueryString["searchGenre"].IsEmpty() ) {
   9:          selectCommand = "SELECT * FROM Movies WHERE Genre = @0";
  10:          searchTerm = Request.QueryString["searchGenre"];
  11:      }
  12:   
  13:      if(!Request.QueryString["searchTitle"].IsEmpty() ) {
  14:        selectCommand = "SELECT * FROM Movies WHERE Title LIKE @0";
  15:        searchTerm = "%" + Request.QueryString["searchTitle"] + "%";
  16:      }
  17:   
  18:      var selectedData = db.Query(selectCommand, searchTerm);
  19:      var grid = new WebGrid(source: selectedData, defaultSort: "Genre", rowsPerPage:3);
  20:  }
  21:    <h2>List Movies</h2>
  22:    <form method="get">
  23:      <div>
  24:        <label for="searchGenre">Genre to look for:</label>
  25:        <input type="text" name="searchGenre"
  26:           value="@Request.QueryString["searchGenre"]" />
  27:        <input type="Submit" value="Search Genre" /><br/>
  28:        (Leave blank to list all movies.)<br/>
  29:      </div>
  30:      <div>
  31:         <label for="SearchTitle">Movie title contains the following:</label>
  32:         <input type="text" name="searchTitle" value="@Request.QueryString["searchTitle"]" />
  33:         <input type="Submit" value="Search Title" /><br/>
  34:      </div>
  35:    </form>
  36:    <div>
  37:      @grid.GetHtml(
  38:          tableStyle: "grid",
  39:          headerStyle: "head",
  40:          alternatingRowStyle: "alt",
  41:          columns: grid.Columns(
  42:              grid.Column(format: @<a href="~/EditMovie?id=@item.ID">Edit</a>),
  43:              grid.Column("Title"),
  44:              grid.Column("Genre"),
  45:              grid.Column("Year"),
  46:              grid.Column(format: @<a href="~/DeleteMovie?id=@item.ID">Delete</a>)
  47:         )
  48:      )
  49:    </div>
  50:    <p><a href="~/AddMovie">Add a movie</a></p>

Testing the Layout

Now you can see what the layout looks like. In WebMatrix, right-click the Movies.cshtml page and select Launch in browser. When the browser displays the page, it looks like this page:

Movies page rendered using a layout
Movies page rendered using a layout

ASP.NET has merged the content of the Movies.cshtml page into the _Layout.cshtml page right where the RenderBody method is. And of course the _Layout.cshtml page references a .css file that defines the look of the page.

Updating the AddMovie Page to Use the Layout

The real benefit of layouts is that you can use them for all the pages in your site. Open the AddMovie.cshtml page.

You might remember that the AddMovie.cshtml page originally had some CSS rules in it to define the look of validation error messages. Since you have a .css file for your site now, you can move those rules to the .css file. Remove them from the AddMovie.cshtml file and add them to the bottom of the Movies.css file. You are moving the following rules:

[!code-cssMain]

   1:  .field-validation-error {
   2:    font-weight:bold;
   3:    color:red;
   4:    background-color:yellow;
   5:   }
   6:  .validation-summary-errors{
   7:    border:2px dashed red;
   8:    color:red;
   9:    background-color:yellow;
  10:    font-weight:bold;
  11:    margin:12px;
  12:  }

Now make the same sorts of changes in AddMovie.cshtml that you did for Movies.cshtml — add Layout="~/_Layout.cshtml; and remove the HTML markup that’s now extraneous. Change the <h1> element to <h2>. When you’re done, the page will look like this example:

[!code-cshtmlMain]

   1:  @{
   2:      Layout = "~/_Layout.cshtml";
   3:      Validation.RequireField("title", "You must enter a title");
   4:      Validation.RequireField("genre", "Genre is required");
   5:      Validation.RequireField("year", "You haven't entered a year");
   6:   
   7:      var title = "";
   8:      var genre = "";
   9:      var year = "";
  10:   
  11:      if(IsPost){
  12:          if(Validation.IsValid()){
  13:              title = Request.Form["title"];
  14:              genre = Request.Form["genre"];
  15:              year = Request.Form["year"];
  16:   
  17:              var db = Database.Open("WebPagesMovies");
  18:              var insertCommand =
  19:                  "INSERT INTO Movies (Title, Genre, Year) Values(@0, @1, @2)";
  20:              db.Execute(insertCommand, title, genre, year);
  21:              Response.Redirect("~/Movies");
  22:          }
  23:      }
  24:  }
  25:    <h2>Add a Movie</h2>
  26:      @Html.ValidationSummary()
  27:   <form method="post">
  28:    <fieldset>
  29:      <legend>Movie Information</legend>
  30:      <p><label for="title">Title:</label>
  31:        <input type="text" name="title" value="@Request.Form["title"]" />
  32:        @Html.ValidationMessage("title")
  33:      </p>
  34:   
  35:      <p><label for="genre">Genre:</label>
  36:        <input type="text" name="genre" value="@Request.Form["genre"]" />
  37:        @Html.ValidationMessage("genre")
  38:      </p>
  39:   
  40:      <p><label for="year">Year:</label>
  41:        <input type="text" name="year" value="@Request.Form["year"]" />
  42:        @Html.ValidationMessage("year")
  43:      </p>
  44:   
  45:      <p><input type="submit" name="buttonSubmit" value="Add Movie" /></p>
  46:    </fieldset>
  47:    </form>

Run the page. Now it looks like this illustration:

‘Add Movies’ page rendered using a layout
‘Add Movies’ page rendered using a layout

You want to make similar changes to the pages in the site — EditMovie.cshtml and DeleteMovie.cshtml. However, before you do, you can make another change to the layout that makes it a little more flexible.

Passing Title Information to the Layout Page

The _Layout.cshtml page that you created has a <title> element that’s set to “My Movie Site”. Most browsers display the content of this element as the text on a tab:

The page’s <title> element displayed in a browser tab
The page’s <title> element displayed in a browser tab

This title information is generic. Suppose that you want the title text to be more specific to the current page. (The title text is also used by search engines to determine what your page is about.) You can pass information from a content page like Movies.cshtml or AddMovie.cshtml to the layout page, and then use that information to customize what the layout page renders.

Open the Movies.cshtml page again. In the code at the top, add the following line:

[!code-csharpMain]

   1:  Page.Title = "List Movies";

The Page object is available on all .cshtml pages and is for this purpose, namely to share information between a page and its layout.

Open the_Layout.cshtml page. Change the <title> element so that it looks like this markup:

[!code-htmlMain]

   1:  <title>@Page.Title</title>

This code renders whatever is in the Page.Title property right at that location in the page.

Run the Movies.cshtml page. This time the browser tab shows what you passed as the value of Page.Title:

A browser tab showing the title created dynamically
A browser tab showing the title created dynamically

If you want, view the page source in the browser. You can see that the <title> element is rendered as <title>List Movies</title>.

[!TIP]

The Page Object

A useful feature of Page is that it’s a dynamic object — the Title property is not a fixed or reserved name. You can use any name for a value of the Page object. For example, you could as easily have passed the title by using a property named Page.CurrentName or Page.MyPage. The only restriction is that the name has to follow the normal rules for what properties can be named. (For example, the name can’t contain a space.)

You can pass any number of values by using the Page object. If you wanted to pass movie information to the layout page, you could pass values by using something like Page.MovieTitle and Page.Genre and Page.MovieYear. (Or any other names that you invented to store the information.) The only requirement — which is probably obvious — is that you have to use the same names in the content page and the layout page.

The information you pass by using the Page object isn’t limited to just text to display on the layout page. You can pass a value to the layout page, and then code in the layout page can use the value to decide whether to display a section of the page, what .css file to use, and so on. The values you pass in the Page object are like any other values that you use in code. It’s just that the values originate in the content page and are passed to the layout page.

Open the AddMovie.cshtml page and add a line to the top of the code that provides a title for the AddMovie.cshtml page:

[!code-csharpMain]

   1:  Page.Title = "Add a Movie";

Run the AddMovie.cshtml page. You see the new title there:

A browser tab showing the ‘Add Movies’ title created dynamically
A browser tab showing the ‘Add Movies’ title created dynamically

Updating the Remaining Pages to Use the Layout

Now you can finish the remaining pages in your site so that they use the new layout. Open EditMovie.cshtml and DeleteMovie.cshtml in turn and make the same changes in each.

Add the line of code that links to the layout page:

[!code-csharpMain]

   1:  Layout = "~/_Layout.cshtml";

Add a line to set the title of the page:

[!code-csharpMain]

   1:  Page.Title = "Edit a Movie";

or:

[!code-csharpMain]

   1:  Page.Title = "Delete a Movie";

Remove all the extraneous HTML markup — basically, leave only the bits that are inside the <body> element (plus the code block at the top).

Change the <h1> element to be an <h2> element.

When you’ve made these changes, test each and make sure that it’s displaying properly and that the title is correct.

Parting Thoughts About Layout Pages

In this tutorial you created a _Layout.cshtml page and used the RenderBody method to merge content from another page. That’s the basic pattern for using layouts in Web Pages.

Layout pages have additional features that we didn’t cover here. For example, you can nest layout pages — one layout page can in turn reference another. Nested layouts can be useful if you’re working with subsections of a site that require different layouts. You can also use additional methods (for example, RenderSection) to set up named sections in the layout page.

The combination of layout pages and .css files is powerful. As you’ll see in the next tutorial series, in WebMatrix you can create a site based on a template, which gives you a site that has prebuilt functionality in it. The templates make good use of layout pages and CSS to create sites that look great and that have features like menus. Here’s a screenshot of the home page from a site based on a template, showing features that use layout pages and CSS:

Layout created by WebMatrix site template showing the header, navigation area, content area, optional section, and login links
Layout created by WebMatrix site template showing the header, navigation area, content area, optional section, and login links

Complete Listing for Movie Page (Updated to Use a Layout Page)

[!code-cshtmlMain]

   1:  @{
   2:      Layout = "~/_Layout.cshtml";
   3:      Page.Title = "List Movies";
   4:   
   5:      var db = Database.Open("WebPagesMovies") ;
   6:      var selectCommand = "SELECT * FROM Movies";
   7:      var searchTerm = "";
   8:   
   9:      if(!Request.QueryString["searchGenre"].IsEmpty() ) {
  10:          selectCommand = "SELECT * FROM Movies WHERE Genre = @0";
  11:          searchTerm = Request.QueryString["searchGenre"];
  12:      }
  13:   
  14:      if(!Request.QueryString["searchTitle"].IsEmpty() ) {
  15:          selectCommand = "SELECT * FROM Movies WHERE Title LIKE @0";
  16:          searchTerm = "%" + Request.QueryString["searchTitle"] + "%";
  17:      }
  18:   
  19:      var selectedData = db.Query(selectCommand, searchTerm);
  20:      var grid = new WebGrid(source: selectedData, defaultSort: "Genre", rowsPerPage:3);
  21:  }
  22:   
  23:  <h2>List Movies</h2>
  24:      <form method="get">
  25:        <div>
  26:          <label for="searchGenre">Genre to look for:</label>
  27:          <input type="text" name="searchGenre" value="@Request.QueryString["searchGenre"]" />
  28:          <input type="Submit" value="Search Genre" /><br/>
  29:          (Leave blank to list all movies.)<br/>
  30:        </div>
  31:   
  32:        <div>
  33:          <label for="SearchTitle">Movie title contains the following:</label>
  34:          <input type="text" name="searchTitle" value="@Request.QueryString["searchTitle"]" />
  35:          <input type="Submit" value="Search Title" /><br/>
  36:        </div>
  37:      </form>
  38:   
  39:  <div>
  40:      @grid.GetHtml(
  41:          tableStyle: "grid",
  42:          headerStyle: "head",
  43:          alternatingRowStyle: "alt",
  44:          columns: grid.Columns(
  45:      grid.Column(format: @<a href="~/EditMovie?id=@item.ID">Edit</a>),
  46:      grid.Column("Title"),
  47:      grid.Column("Genre"),
  48:      grid.Column("Year"),
  49:      grid.Column(format: @<a href="~/DeleteMovie?id=@item.ID">Delete</a>)
  50:          )
  51:      )
  52:  </div>
  53:  <p><a href="~/AddMovie">Add a movie</a></p>

Complete Page Listing for Add Movie Page (Updated for Layout)

[!code-cshtmlMain]

   1:  @{
   2:      Layout = "~/_Layout.cshtml";
   3:      Page.Title = "Add a Movie";
   4:   
   5:      Validation.RequireField("title", "You must enter a title");
   6:      Validation.RequireField("genre", "Genre is required");
   7:      Validation.RequireField("year", "You haven't entered a year");
   8:   
   9:      var title = "";
  10:      var genre = "";
  11:      var year = "";
  12:   
  13:      if(IsPost){
  14:          if(Validation.IsValid()){
  15:              title = Request.Form["title"];
  16:              genre = Request.Form["genre"];
  17:              year = Request.Form["year"];
  18:   
  19:              var db = Database.Open("WebPagesMovies");
  20:              var insertCommand = "INSERT INTO Movies (Title, Genre, Year) VALUES(@0, @1, @2)";
  21:              db.Execute(insertCommand, title, genre, year);
  22:   
  23:              Response.Redirect("~/Movies");
  24:          }
  25:      }
  26:  }
  27:   
  28:  <h2>Add a Movie</h2>
  29:  @Html.ValidationSummary()
  30:  <form method="post">
  31:  <fieldset>
  32:      <legend>Movie Information</legend>
  33:      <p><label for="title">Title:</label>
  34:          <input type="text" name="title" value="@Request.Form["title"]" />
  35:          @Html.ValidationMessage("title")
  36:   
  37:      <p><label for="genre">Genre:</label>
  38:          <input type="text" name="genre" value="@Request.Form["genre"]" />
  39:          @Html.ValidationMessage("genre")
  40:   
  41:      <p><label for="year">Year:</label>
  42:          <input type="text" name="year" value="@Request.Form["year"]" />
  43:          @Html.ValidationMessage("year")
  44:   
  45:      <p><input type="submit" name="buttonSubmit" value="Add Movie" /></p>
  46:  </fieldset>
  47:  </form>

Complete Page Listing for Delete Movie Page (Updated for Layout)

[!code-cshtmlMain]

   1:  @{
   2:      Layout = "~/_Layout.cshtml";
   3:      Page.Title = "Delete a Movie";
   4:   
   5:      var title = "";
   6:      var genre = "";
   7:      var year = "";
   8:      var movieId = "";
   9:   
  10:      if(!IsPost){
  11:          if(!Request.QueryString["ID"].IsEmpty() && Request.QueryString["ID"].AsInt() > 0){
  12:              movieId = Request.QueryString["ID"];
  13:              var db = Database.Open("WebPagesMovies");
  14:              var dbCommand = "SELECT * FROM Movies WHERE ID = @0";
  15:              var row = db.QuerySingle(dbCommand, movieId);
  16:              if(row != null) {
  17:                  title = row.Title;
  18:                  genre = row.Genre;
  19:                  year = row.Year;
  20:              }
  21:              else{
  22:                  Validation.AddFormError("No movie was found for that ID.");
  23:                  // If you are using a version of ASP.NET Web Pages 2 that's
  24:                  // earlier than the RC release, comment out the preceding
  25:                  // statement and uncomment the following one.
  26:                  //ModelState.AddFormError("No movie was found for that ID.");
  27:              }
  28:          }
  29:          else{
  30:              Validation.AddFormError("No movie was found for that ID.");
  31:              // If you are using a version of ASP.NET Web Pages 2 that's
  32:              // earlier than the RC release, comment out the preceding
  33:              // statement and uncomment the following one.
  34:              //ModelState.AddFormError("No movie was found for that ID.");
  35:          }
  36:      }
  37:   
  38:      if(IsPost && !Request["buttonDelete"].IsEmpty()){
  39:          movieId = Request.Form["movieId"];
  40:          var db = Database.Open("WebPagesMovies");
  41:          var deleteCommand = "DELETE FROM Movies WHERE ID = @0";
  42:          db.Execute(deleteCommand, movieId);
  43:          Response.Redirect("~/Movies");
  44:      }
  45:   
  46:  }
  47:   
  48:  <h2>Delete a Movie</h2>
  49:  @Html.ValidationSummary()
  50:  <p><a href="~/Movies">Return to movie listing</a></p>
  51:   
  52:  <form method="post">
  53:  <fieldset>
  54:  <legend>Movie Information</legend>
  55:   
  56:  <p><span>Title:</span>
  57:      <span>@title</span></p>
  58:   
  59:  <p><span>Genre:</span>
  60:      <span>@genre</span></p>
  61:   
  62:  <p><span>Year:</span>
  63:      <span>@year</span></p>
  64:   
  65:  <input type="hidden" name="movieid" value="@movieId" />
  66:  <p><input type="submit" name="buttonDelete" value="Delete Movie" /></p>
  67:  </fieldset>
  68:  </form>

Complete Page Listing for Edit Movie Page (Updated for Layout)

[!code-cshtmlMain]

   1:  @{
   2:      Layout = "~/_Layout.cshtml";
   3:      Page.Title = "Edit a Movie";
   4:   
   5:      var title = "";
   6:      var genre = "";
   7:      var year = "";
   8:      var movieId = "";
   9:   
  10:      if(!IsPost){
  11:          if(!Request.QueryString["ID"].IsEmpty() && Request.QueryString["ID"].IsInt()) {
  12:              movieId = Request.QueryString["ID"];
  13:              var db = Database.Open("WebPagesMovies");
  14:              var dbCommand = "SELECT * FROM Movies WHERE ID = @0";
  15:              var row = db.QuerySingle(dbCommand, movieId);
  16:   
  17:              if(row != null) {
  18:                  title = row.Title;
  19:                  genre = row.Genre;
  20:                  year = row.Year;
  21:              }
  22:              else{
  23:                  Validation.AddFormError("No movie was selected.");
  24:                  // If you are using a version of ASP.NET Web Pages 2 that's
  25:                  // earlier than the RC release, comment out the preceding
  26:                  // statement and uncomment the following one.
  27:                  //ModelState.AddFormError("No movie was selected.");
  28:              }
  29:          }
  30:          else{
  31:              Validation.AddFormError("No movie was selected.");
  32:              // If you are using a version of ASP.NET Web Pages 2 that's
  33:              // earlier than the RC release, comment out the preceding
  34:              // statement and uncomment the following one.
  35:              //ModelState.AddFormError("No movie was selected.");
  36:          }
  37:      }
  38:   
  39:      if(IsPost){
  40:          Validation.RequireField("title", "You must enter a title");
  41:          Validation.RequireField("genre", "Genre is required");
  42:          Validation.RequireField("year", "You haven't entered a year");
  43:          Validation.RequireField("movieid", "No movie ID was submitted!");
  44:   
  45:          title = Request.Form["title"];
  46:          genre = Request.Form["genre"];
  47:          year = Request.Form["year"];
  48:          movieId = Request.Form["movieId"];
  49:   
  50:          if(Validation.IsValid()){
  51:              var db = Database.Open("WebPagesMovies");
  52:              var updateCommand = "UPDATE Movies SET Title=@0, Genre=@1, Year=@2 WHERE Id=@3";
  53:              db.Execute(updateCommand, title, genre, year, movieId);
  54:              Response.Redirect("~/Movies");
  55:          }
  56:      }
  57:  }
  58:   
  59:  <h2>Edit a Movie</h2>
  60:  @Html.ValidationSummary()
  61:  <form method="post">
  62:  <fieldset>
  63:      <legend>Movie Information</legend>
  64:   
  65:      <p><label for="title">Title:</label>
  66:          <input type="text" name="title" value="@title" /></p>
  67:   
  68:      <p><label for="genre">Genre:</label>
  69:          <input type="text" name="genre" value="@genre" /></p>
  70:   
  71:      <p><label for="year">Year:</label>
  72:          <input type="text" name="year" value="@year" /></p>
  73:   
  74:      <input type="hidden" name="movieid" value="@movieId" />
  75:   
  76:      <p><input type="submit" name="buttonSubmit" value="Submit Changes" /></p>
  77:  </fieldset>
  78:  </form>
  79:  <p><a href="~/Movies">Return to movie listing</a></p>

Coming Up Next

In the next tutorial, you’ll learn how to publish your site to the Internet so everyone can see it.

Additional Resources

Previous Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-pages/overview/getting-started/introducing-aspnet-web-pages-2/layouts.htm
< THANKS ME>