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

ASP.NET MVC 4 Helpers, Forms and Validation

by Web Camps Team

In ASP.NET MVC 4 Models and Data Access Hands-on Lab, you have been loading and displaying data from the database. In this Hands-on Lab, you will add to the Music Store application the ability to edit that data.

With that goal in mind, you will first create the controller that will support the Create, Read, Update and Delete (CRUD) actions of albums. You will generate an Index View template taking advantage of ASP.NET MVC’s scaffolding feature to display the albums’ properties in an HTML table. To enhance that view, you will add a custom HTML helper that will truncate long descriptions.

Afterwards, you will add the Edit and Create Views that will let you alter the albums in the database, with the help of form elements like dropdowns.

Lastly, you will let users delete an album and also you will prevent them from entering wrong data by validating their input.

[!NOTE] This Hands-on Lab assumes you have basic knowledge of ASP.NET MVC. If you have not used ASP.NET MVC before, we recommend you to go over ASP.NET MVC Fundamentals Hands-on Lab.

This lab walks you through the enhancements and new features previously described by applying minor changes to a sample Web application provided in the Source folder.

All sample code and snippets are included in the Web Camps Training Kit, available at https://www.microsoft.com/en-us/download/29843.

### Objectives

In this Hands-On Lab, you will learn how to:

### Prerequisites

You must have the following items to complete this lab:

### Setup

Installing Code Snippets

For convenience, much of the code you will be managing along this lab is available as Visual Studio code snippets. To install the code snippets run ..vsi file.

If you are not familiar with the Visual Studio Code Snippets, and want to learn how to use them, you can refer to the appendix from this document “Appendix B: Using Code Snippets”.


## Exercises

The following exercises make up this Hands-On Lab:

  1. Creating the Store Manager controller and its Index view
  2. Adding an HTML Helper
  3. Creating the Edit View
  4. Adding a Create View
  5. Handling Deletion
  6. Adding Validation
  7. Using Unobtrusive jQuery at Client Side

[!NOTE] Each exercise is accompanied by an End folder containing the resulting solution you should obtain after completing the exercises. You can use this solution as a guide if you need additional help working through the exercises.

Estimated time to complete this lab: 60 minutes

### Exercise 1: Creating the Store Manager controller and its Index view

In this exercise, you will learn how to create a new controller to support CRUD operations, customize its Index action method to return a list of albums from the database and finally generating an Index View template taking advantage of ASP.NET MVC’s scaffolding feature to display the albums’ properties in an HTML table.

#### Task 1 - Creating the StoreManagerController

In this task, you will create a new controller called StoreManagerController to support CRUD operations.

  1. Open the Begin solution located at Source/Ex1-CreatingTheStoreManagerController/Begin/ folder.

    1. You will need to download some missing NuGet packages before continue. To do this, click the Project menu and select Manage NuGet Packages.
    2. In the Manage NuGet Packages dialog, click Restore in order to download missing packages.
    3. Finally, build the solution by clicking Build | Build Solution.

    [!NOTE] One of the advantages of using NuGet is that you don’t have to ship all the libraries in your project, reducing the project size. With NuGet Power Tools, by specifying the package versions in the Packages.config file, you will be able to download all the required libraries the first time you run the project. This is why you will have to run these steps after you open an existing solution from this lab.

  2. Add a new controller. To do this, right-click the Controllers folder within the Solution Explorer, select Add and then the Controller command. Change the Controller Name to StoreManagerController and make sure the option MVC controller with empty read/write actions is selected. Click Add.

    Add controller dialog
    Add controller dialog

    Add Controller Dialog

    A new Controller class is generated. Since you indicated to add actions for read/write, stub methods for those, common CRUD actions are created with TODO comments filled in, prompting to include the application specific logic.

#### Task 2 - Customizing the StoreManager Index

In this task, you will customize the StoreManager Index action method to return a View with the list of albums from the database.

  1. In the StoreManagerController class, add the following using directives.

    (Code Snippet - ASP.NET MVC 4 Helpers and Forms and Validation - Ex1 using MvcMusicStore)

    [!code-csharpMain]
       1:  using System.Data;
       2:  using System.Data.Entity;
       3:  using MvcMusicStore.Models;
  2. Add a field to the StoreManagerController to hold an instance of MusicStoreEntities.

    (Code Snippet - ASP.NET MVC 4 Helpers and Forms and Validation - Ex1 MusicStoreEntities)

    [!code-csharpMain]
       1:  public class StoreManagerController : Controller
       2:  {
       3:      private MusicStoreEntities db = new MusicStoreEntities();
  3. Implement the StoreManagerController Index action to return a View with the list of albums.

    The Controller action logic will be very similar to the StoreController’s Index action written earlier. Use LINQ to retrieve all albums, including Genre and Artist information for display.

    (Code Snippet - ASP.NET MVC 4 Helpers and Forms and Validation - Ex1 StoreManagerController Index)

    [!code-csharpMain]

       1:  //
       2:  // GET: /StoreManager/
       3:   
       4:  public ActionResult Index()
       5:  {
       6:      var albums = this.db.Albums.Include(a => a.Genre).Include(a => a.Artist)
       7:           .OrderBy(a => a.Price);
       8:   
       9:      return this.View(albums.ToList());
      10:  }

#### Task 3 - Creating the Index View

In this task, you will create the Index View template to display the list of albums returned by the StoreManager Controller.

  1. Before creating the new View template, you should build the project so that the Add View Dialog knows about the Album class to use. Select Build | Build MvcMusicStore to build the project.
  2. Right-click inside the Index action method and select Add View. This will bring up the Add View dialog.

    Add view
    Add view
    Adding a View from within the Index method
  3. In the Add View dialog, verify that the View Name is Index. Select the Create a strongly-typed view option, and select Album (MvcMusicStore.Models) from the Model class drop-down. Select List from the Scaffold template drop-down. Leave the View engine to Razor and the other fields with their default value and then click Add.

    Adding an index view
    Adding an index view

    Adding an Index View

#### Task 4 - Customizing the scaffold of the Index View

In this task, you will adjust the simple View template created with ASP.NET MVC scaffolding feature to have it display the fields you want.

[!NOTE] The scaffolding support within ASP.NET MVC generates a simple View template which lists all fields in the Album model. Scaffolding provides a quick way to get started on a strongly typed view: rather than having to write the View template manually, scaffolding quickly generates a default template and then you can modify the generated code.

  1. Review the code created. The generated list of fields will be part of the following HTML table that Scaffolding is using for displaying tabular data.

    [!code-cshtmlMain]
       1:  @model IEnumerable<MvcMusicStore.Models.Album>
       2:   
       3:  @{
       4:       ViewBag.Title = "Index";
       5:  }
       6:   
       7:  <h2>Index</h2>
       8:   
       9:  <p>
      10:       @Html.ActionLink("Create New", "Create")
      11:  </p>
      12:  <table>
      13:       <tr>
      14:            <th>
      15:                  @Html.DisplayNameFor(model => model.GenreId)
      16:            </th>
      17:            <th>
      18:                  @Html.DisplayNameFor(model => model.ArtistId)
      19:            </th>
      20:            <th>
      21:                  @Html.DisplayNameFor(model => model.Title)
      22:            </th>
      23:            <th>
      24:                  @Html.DisplayNameFor(model => model.Price)
      25:            </th>
      26:            <th>
      27:                  @Html.DisplayNameFor(model => model.AlbumArtUrl)
      28:            </th>
      29:            <th></th>
      30:       </tr>
      31:   
      32:  @foreach (var item in Model) {
      33:       <tr>
      34:            <td>
      35:                  @Html.DisplayFor(modelItem => item.GenreId)
      36:            </td>
      37:            <td>
      38:                  @Html.DisplayFor(modelItem => item.ArtistId)
      39:            </td>
      40:            <td>
      41:                  @Html.DisplayFor(modelItem => item.Title)
      42:            </td>
      43:            <td>
      44:                  @Html.DisplayFor(modelItem => item.Price)
      45:            </td>
      46:            <td>
      47:                  @Html.DisplayFor(modelItem => item.AlbumArtUrl)
      48:            </td>
      49:            <td>
      50:                  @Html.ActionLink("Edit", "Edit", new { id=item.AlbumId }) |
      51:                  @Html.ActionLink("Details", "Details", new { id=item.AlbumId }) |
      52:                  @Html.ActionLink("Delete", "Delete", new { id=item.AlbumId })
      53:            </td>
      54:       </tr>
      55:  }
      56:   
      57:  </table>
  2. Replace the <table> code with the following code to display only the Genre, Artist, Album Title, and Price fields. This deletes the AlbumId and Album Art URL columns. Also, it changes GenreId and ArtistId columns to display their linked class properties of Artist.Name and Genre.Name, and removes the Details link.

    [!code-cshtmlMain]
       1:  <table>
       2:      <tr>
       3:        <th></th>
       4:        <th>Genre</th>
       5:        <th>Artist</th>
       6:        <th>Title</th>
       7:        <th>Price</th>
       8:      </tr>
       9:   
      10:      @foreach (var item in Model) {
      11:       <tr>
      12:            <td>
      13:                  @Html.ActionLink("Edit", "Edit", new { id=item.AlbumId }) |
      14:   
      15:                  @Html.ActionLink("Delete", "Delete", new { id=item.AlbumId })
      16:            </td>
      17:            <td>
      18:                  @Html.DisplayFor(modelItem => item.Genre.Name)
      19:            </td>
      20:            <td>
      21:                  @Html.DisplayFor(modelItem => item.Artist.Name)
      22:            </td>
      23:            <td>
      24:                  @Html.DisplayFor(modelItem => item.Title)
      25:            </td>
      26:            <td>
      27:                  @Html.DisplayFor(modelItem => item.Price)
      28:            </td>
      29:       </tr>
      30:      }
      31:  </table>
  3. Change the following descriptions.

    [!code-cshtmlMain]

       1:  @model IEnumerable<MvcMusicStore.Models.Album>
       2:  @{
       3:      ViewBag.Title = "Store Manager - All Albums";
       4:  }
       5:   
       6:  <h2>Albums</h2>

#### Task 5 - Running the Application

In this task, you will test that the StoreManager Index View template displays a list of albums according to the design of the previous steps.

  1. Press F5 to run the Application.
  2. The project starts in the Home page. Change the URL to /StoreManager to verify that a list of albums is displayed, showing their Title, Artist and Genre.

    Browsing the list of albums
    Browsing the list of albums

    Browsing the list of albums

### Exercise 2: Adding an HTML Helper

The StoreManager Index page has one potential issue: Title and Artist Name properties can both be long enough to throw off the table formatting. In this exercise you will learn how to add a custom HTML helper to truncate that text.

In the following figure, you can see how the format is modified because of the length of the text when you use a small browser size.

Browsing the list of Albums with not truncated text
Browsing the list of Albums with not truncated text

Browsing the list of Albums with not truncated text

#### Task 1 - Extending the HTML Helper

In this task, you will add a new method Truncate to the HTML object exposed within ASP.NET MVC Views. To do this, you will implement an extension method to the built-in System.Web.Mvc.HtmlHelper class provided by ASP.NET MVC.

[!NOTE] To read more about Extension Methods, please visit this msdn article. https://msdn.microsoft.com/en-us/library/bb383977.aspx.

  1. Open the Begin solution located at Source/Ex2-AddingAnHTMLHelper/Begin/ folder. Otherwise, you might continue using the End solution obtained by completing the previous exercise.

    1. If you opened the provided Begin solution, you will need to download some missing NuGet packages before continue. To do this, click the Project menu and select Manage NuGet Packages.
    2. In the Manage NuGet Packages dialog, click Restore in order to download missing packages.
    3. Finally, build the solution by clicking Build | Build Solution.

    [!NOTE] One of the advantages of using NuGet is that you don’t have to ship all the libraries in your project, reducing the project size. With NuGet Power Tools, by specifying the package versions in the Packages.config file, you will be able to download all the required libraries the first time you run the project. This is why you will have to run these steps after you open an existing solution from this lab.

  2. Open StoreManager’s Index View. To do this, in the Solution Explorer expand the Views folder, then the StoreManager and open the Index.cshtml file.
  3. Add the following code below the @model directive to define the Truncate helper method.

    [!code-cshtmlMain]

       1:  @model IEnumerable<MvcMusicStore.Models.Album>
       2:   
       3:  @helper Truncate(string input, int length)
       4:  {
       5:       if (input.Length <= length) {
       6:            @input
       7:       } else {
       8:            @input.Substring(0, length)<text>...</text>
       9:       }
      10:  } 
      11:   
      12:  @{
      13:       ViewBag.Title = "Store Manager - All Albums";
      14:  }
      15:   
      16:  <h2>Albums</h2>

#### Task 2 - Truncating Text in the Page

In this task, you will use the Truncate method to truncate the text in the View template.

  1. Open StoreManager’s Index View. To do this, in the Solution Explorer expand the Views folder, then the StoreManager and open the Index.cshtml file.
  2. Replace the lines that show the Artist Name and Album’s Title. To do this, replace the following lines.

    [!code-cshtmlMain]

       1:  <tr>
       2:       <td>
       3:            @Html.ActionLink("Edit", "Edit", new { id=item.AlbumId }) |
       4:   
       5:            @Html.ActionLink("Delete", "Delete", new { id=item.AlbumId })
       6:       </td>
       7:       <td>
       8:            @Html.DisplayFor(modelItem => item.Genre.Name)
       9:       </td>
      10:       <td>
      11:            @Truncate(item.Artist.Name, 25)
      12:       </td>
      13:       <td>
      14:            @Truncate(item.Title, 25)
      15:       </td>
      16:       <td>
      17:            @Html.DisplayFor(modelItem => item.Price)
      18:       </td>
      19:  </tr>

#### Task 3 - Running the Application

In this task, you will test that the StoreManager Index View template truncates the Album’s Title and Artist Name.

  1. Press F5 to run the Application.
  2. The project starts in the Home page. Change the URL to /StoreManager to verify that long texts in the Title and Artist column are truncated.

    Truncated titles and artists names
    Truncated titles and artists names

    Truncated Titles and Artist Names

### Exercise 3: Creating the Edit View

In this exercise, you will learn how to create a form to allow store managers to edit an Album. They will browse the /StoreManager/Edit/id URL (id being the unique id of the album to edit), thus making an HTTP-GET call to the server.

The Controller Edit action method will retrieve the appropriate Album from the database, create a StoreManagerViewModel object to encapsulate it (along with a list of Artists and Genres), and then pass it off to a View template to render the HTML page back to the user. This page will contain a <form> element with textboxes and dropdowns for editing the Album properties.

Once the user updates the Album form values and clicks the Save button, the changes are submitted via an HTTP-POST call back to /StoreManager/Edit/id. Although the URL remains the same as in the last call, ASP.NET MVC identifies that this time it is an HTTP-POST and therefore executes a different Edit action method (one decorated with [HttpPost]).

#### Task 1 - Implementing the HTTP-GET Edit Action Method

In this task, you will implement the HTTP-GET version of the Edit action method to retrieve the appropriate Album from the database, as well as a list of all Genres and Artists. It will package this data up into the StoreManagerViewModel object defined in the last step, which will then be passed to a View template to render the response with.

  1. Open the Begin solution located at Source/Ex3-CreatingTheEditView/Begin/ folder. Otherwise, you might continue using the End solution obtained by completing the previous exercise.

    1. If you opened the provided Begin solution, you will need to download some missing NuGet packages before continue. To do this, click the Project menu and select Manage NuGet Packages.
    2. In the Manage NuGet Packages dialog, click Restore in order to download missing packages.
    3. Finally, build the solution by clicking Build | Build Solution.

    [!NOTE] One of the advantages of using NuGet is that you don’t have to ship all the libraries in your project, reducing the project size. With NuGet Power Tools, by specifying the package versions in the Packages.config file, you will be able to download all the required libraries the first time you run the project. This is why you will have to run these steps after you open an existing solution from this lab.

  2. Open the StoreManagerController class. To do this, expand the Controllers folder and double-click StoreManagerController.cs.
  3. Replace the HTTP-GET Edit action method with the following code to retrieve the appropriate Album as well as the Genres and Artists lists.

    (Code Snippet - ASP.NET MVC 4 Helpers and Forms and Validation - Ex3 StoreManagerController HTTP-GET Edit action)

    [!code-csharpMain]

       1:  public ActionResult Edit(int id)
       2:  {
       3:      Album album = this.db.Albums.Find(id);
       4:   
       5:      if (album == null)
       6:      {
       7:           return this.HttpNotFound();
       8:      }
       9:   
      10:      this.ViewBag.GenreId = new SelectList(this.db.Genres, "GenreId", "Name", album.GenreId);
      11:      this.ViewBag.ArtistId = new SelectList(this.db.Artists, "ArtistId", "Name", album.ArtistId);
      12:   
      13:      return this.View(album);
      14:  }

    [!NOTE] You are using System.Web.Mvc SelectList for Artists and Genres instead of the System.Collections.Generic List.

    SelectList is a cleaner way to populate HTML dropdowns and manage things like current selection. Instantiating and later setting up these ViewModel objects in the controller action will make the Edit form scenario cleaner.

#### Task 2 - Creating the Edit View

In this task, you will create an Edit View template that will later display the album properties.

  1. Create the Edit View. To do this, right-click inside the Edit action method and select Add View.
  2. In the Add View dialog, verify that the View Name is Edit. Check the Create a strongly-typed view checkbox and select Album (MvcMusicStore.Models) from the View data class drop-down. Select Edit from the Scaffold template drop-down. Leave the other fields with their default value and then click Add.

    Adding an Edit view
    Adding an Edit view

    Adding an Edit view

#### Task 3 - Running the Application

In this task, you will test that the StoreManager Edit View page displays the properties’ values for the album passed as parameter.

  1. Press F5 to run the Application.
  2. The project starts in the Home page. Change the URL to /StoreManager/Edit/1 to verify that the properties’ values for the album passed are displayed.

    Browsing Album’s Edit View
    Browsing Album’s Edit View

    Browsing Album’s Edit view

#### Task 4 - Implementing drop-downs on the Album Editor Template

In this task, you will add drop-downs to the View template created in the last task, so that the user can select from a list of Artists and Genres.

  1. Replace all the Album fieldset code with the following:

    [!code-cshtmlMain]

       1:  <fieldset>
       2:       <legend>Album</legend>
       3:   
       4:       @Html.HiddenFor(model => model.AlbumId)
       5:   
       6:       <div class="editor-label">
       7:            @Html.LabelFor(model => model.Title)
       8:       </div>
       9:       <div class="editor-field">
      10:            @Html.EditorFor(model => model.Title)
      11:            @Html.ValidationMessageFor(model => model.Title)
      12:       </div>
      13:   
      14:       <div class="editor-label">
      15:            @Html.LabelFor(model => model.Price)
      16:       </div>
      17:       <div class="editor-field">
      18:            @Html.EditorFor(model => model.Price)
      19:            @Html.ValidationMessageFor(model => model.Price)
      20:       </div>
      21:   
      22:       <div class="editor-label">
      23:            @Html.LabelFor(model => model.AlbumArtUrl)
      24:       </div>
      25:       <div class="editor-field">
      26:            @Html.EditorFor(model => model.AlbumArtUrl)
      27:            @Html.ValidationMessageFor(model => model.AlbumArtUrl)
      28:       </div>
      29:   
      30:       <div class="editor-label">
      31:            @Html.LabelFor(model => model.Artist)
      32:       </div>
      33:       <div class="editor-field">
      34:            @Html.DropDownList("ArtistId", (SelectList) ViewData["Artists"])
      35:            @Html.ValidationMessageFor(model => model.ArtistId)
      36:       </div>
      37:   
      38:       <div class="editor-label">
      39:            @Html.LabelFor(model => model.Genre)
      40:       </div>
      41:       <div class="editor-field">
      42:            @Html.DropDownList("GenreId", (SelectList) ViewData["Genres"])
      43:            @Html.ValidationMessageFor(model => model.GenreId)
      44:       </div>
      45:   
      46:       <p>
      47:            <input type="submit" value="Save" />
      48:       </p>
      49:  </fieldset>

    [!NOTE] An Html.DropDownList helper has been added to render drop-downs for choosing Artists and Genres. The parameters passed to Html.DropDownList are:

    1. The name of the form field (“ArtistId”).
    2. The SelectList of values for the drop-down.

#### Task 5 - Running the Application

In this task, you will test that the StoreManager Edit View page displays drop-downs instead of Artist and Genre ID text fields.

  1. Press F5 to run the Application.
  2. The project starts in the Home page. Change the URL to /StoreManager/Edit/1 to verify that it displays drop-downs instead of Artist and Genre ID text fields.

    Browsing Album’s Edit View with drop downs
    Browsing Album’s Edit View with drop downs

    Browsing Album’s Edit view, this time with dropdowns

#### Task 6 - Implementing the HTTP-POST Edit action method

Now that the Edit View displays as expected, you need to implement the HTTP-POST Edit Action method to save the changes made to the Album.

  1. Close the browser if needed, to return to the Visual Studio window. Open StoreManagerController from the Controllers folder.
  2. Replace HTTP-POST Edit action method code with the following (note that the method that must be replaced is overloaded version that receives two parameters):

    (Code Snippet - ASP.NET MVC 4 Helpers and Forms and Validation - Ex3 StoreManagerController HTTP-POST Edit action)

    [!code-csharpMain]

       1:  [HttpPost]
       2:  public ActionResult Edit(Album album)
       3:  {
       4:       if (ModelState.IsValid)
       5:       {
       6:            this.db.Entry(album).State = EntityState.Modified;
       7:            this.db.SaveChanges();
       8:   
       9:            return this.RedirectToAction("Index");
      10:       }
      11:   
      12:       this.ViewBag.GenreId = new SelectList(this.db.Genres, "GenreId", "Name", album.GenreId);
      13:       this.ViewBag.ArtistId = new SelectList(this.db.Artists, "ArtistId", "Name", album.ArtistId);
      14:   
      15:       return this.View(album);
      16:  }

    [!NOTE] This method will be executed when the user clicks the Save button of the View and performs an HTTP-POST of the form values back to the server to persist them in the database. The decorator [HttpPost] indicates that the method should be used for those HTTP-POST scenarios. The method takes an Album object. ASP.NET MVC will automatically create the Album object from the posted <form> values.

    The method will perform these steps:

    1. If model is valid:

      1. Update the album entry in the context to mark it as a modified object.
      2. Save the changes and redirect to the index view.
    2. If the model is not valid, it will populate the ViewBag with the GenreId and ArtistId, then it will return the view with the received Album object to allow the user perform any required update.

#### Task 7 - Running the Application

In this task, you will test that the StoreManager Edit View page actually saves the updated Album data in the database.

  1. Press F5 to run the Application.
  2. The project starts in the Home page. Change the URL to /StoreManager/Edit/1. Change the Album title to Load and click on Save. Verify that album’s title actually changed in the list of albums.

    Updating an album
    Updating an album

    Updating an Album

### Exercise 4: Adding a Create View

Now that the StoreManagerController supports the Edit ability, in this exercise you will learn how to add a Create View template to let store managers add new Albums to the application.

Like you did with the Edit functionality, you will implement the Create scenario using two separate methods within the StoreManagerController class:

  1. One action method will display an empty form when store managers first visit the /StoreManager/Create URL.
  2. A second action method will handle the scenario where the store manager clicks the Save button within the form and submits the values back to the /StoreManager/Create URL as an HTTP-POST.

#### Task 1 - Implementing the HTTP-GET Create action method

In this task, you will implement the HTTP-GET version of the Create action method to retrieve a list of all Genres and Artists, package this data up into a StoreManagerViewModel object, which will then be passed to a View template.

  1. Open the Begin solution located at Source/Ex4-AddingACreateView/Begin/ folder. Otherwise, you might continue using the End solution obtained by completing the previous exercise.

    1. If you opened the provided Begin solution, you will need to download some missing NuGet packages before continue. To do this, click the Project menu and select Manage NuGet Packages.
    2. In the Manage NuGet Packages dialog, click Restore in order to download missing packages.
    3. Finally, build the solution by clicking Build | Build Solution.

    [!NOTE] One of the advantages of using NuGet is that you don’t have to ship all the libraries in your project, reducing the project size. With NuGet Power Tools, by specifying the package versions in the Packages.config file, you will be able to download all the required libraries the first time you run the project. This is why you will have to run these steps after you open an existing solution from this lab.

  2. Open StoreManagerController class. To do this, expand the Controllers folder and double-click StoreManagerController.cs.
  3. Replace the Create action method code with the following:

    (Code Snippet - ASP.NET MVC 4 Helpers and Forms and Validation - Ex4 StoreManagerController HTTP-GET Create action)

    [!code-csharpMain]

       1:  //
       2:  // GET: /StoreManager/Create
       3:   
       4:  public ActionResult Create()
       5:  {
       6:       this.ViewBag.GenreId = new SelectList(this.db.Genres, "GenreId", "Name");
       7:       this.ViewBag.ArtistId = new SelectList(this.db.Artists, "ArtistId", "Name");
       8:   
       9:       return this.View();
      10:  }

#### Task 2 - Adding the Create View

In this task, you will add the Create View template that will display a new (empty) Album form.

  1. Right-click inside the Create action method and select Add View. This will bring up the Add View dialog.
  2. In the Add View dialog, verify that the View Name is Create. Select the Create a strongly-typed view option and select Album (MvcMusicStore.Models) from the Model class drop-down and Create from the Scaffold template drop-down. Leave the other fields with their default value and then click Add.

    Adding a create view
    Adding a create view
    Adding the Create View
  3. Update the GenreId and ArtistId fields to use a drop-down list as shown below:

    [!code-cshtmlMain]

       1:  ...
       2:  <fieldset>
       3:       <legend>Album</legend>
       4:   
       5:       <div class="editor-label">
       6:            @Html.LabelFor(model => model.GenreId, "Genre")
       7:       </div>
       8:       <div class="editor-field">
       9:            @Html.DropDownList("GenreId", String.Empty)
      10:            @Html.ValidationMessageFor(model => model.GenreId)
      11:       </div>
      12:   
      13:       <div class="editor-label">
      14:            @Html.LabelFor(model => model.ArtistId, "Artist")
      15:       </div>
      16:       <div class="editor-field">
      17:            @Html.DropDownList("ArtistId", String.Empty)
      18:            @Html.ValidationMessageFor(model => model.ArtistId)
      19:       </div>
      20:   
      21:       <div class="editor-label">
      22:            @Html.LabelFor(model => model.Title)
      23:       </div>
      24:      ...

#### Task 3 - Running the Application

In this task, you will test that the StoreManager Create View page displays an empty Album form.

  1. Press F5 to run the Application.
  2. The project starts in the Home page. Change the URL to /StoreManager/Create. Verify that an empty form is displayed for filling the new Album properties.

    Create View with an empty form
    Create View with an empty form

    Create View with an empty form

#### Task 4 - Implementing the HTTP-POST Create Action Method

In this task, you will implement the HTTP-POST version of the Create action method that will be invoked when a user clicks the Save button. The method should save the new album in the database.

  1. Close the browser if needed, to return to the Visual Studio window. Open StoreManagerController class. To do this, expand the Controllers folder and double-click StoreManagerController.cs.
  2. Replace HTTP-POST Create action method code with the following:

    (Code Snippet - ASP.NET MVC 4 Helpers and Forms and Validation - Ex4 StoreManagerController HTTP- POST Create action)

    [!code-csharpMain]

       1:  [HttpPost]
       2:  public ActionResult Create(Album album)
       3:  {
       4:       if (ModelState.IsValid)
       5:       {
       6:            this.db.Albums.Add(album);
       7:            this.db.SaveChanges();
       8:   
       9:            return this.RedirectToAction("Index");
      10:       }
      11:   
      12:       this.ViewBag.GenreId = new SelectList(this.db.Genres, "GenreId", "Name", album.GenreId);
      13:       this.ViewBag.ArtistId = new SelectList(this.db.Artists, "ArtistId", "Name", album.ArtistId);
      14:   
      15:       return this.View(album);
      16:  }

    [!NOTE] The Create action is pretty similar to the previous Edit action method but instead of setting the object as modified, it is being added to the context.

#### Task 5 - Running the Application

In this task, you will test that the StoreManager Create View page lets you create a new Album and then redirects to the StoreManager Index View.

  1. Press F5 to run the Application.
  2. The project starts in the Home page. Change the URL to /StoreManager/Create. Fill all the form fields with data for a new Album, like the one in the following figure:

    Creating an Album
    Creating an Album
    Creating an Album
  3. Verify that you get redirected to the StoreManager Index View that includes the new Album just created.

    New Album Created
    New Album Created

    New Album Created

### Exercise 5: Handling Deletion

The ability to delete albums is not yet implemented. This is what this exercise will be about. Like before, you will implement the Delete scenario using two separate methods within the StoreManagerController class:

  1. One action method will display a confirmation form
  2. A second action method will handle the form submission

#### Task 1 - Implementing the HTTP-GET Delete Action Method

In this task, you will implement the HTTP-GET version of the Delete action method to retrieve the album’s information.

  1. Open the Begin solution located at Source/Ex5-HandlingDeletion/Begin/ folder. Otherwise, you might continue using the End solution obtained by completing the previous exercise.

    1. If you opened the provided Begin solution, you will need to download some missing NuGet packages before continue. To do this, click the Project menu and select Manage NuGet Packages.
    2. In the Manage NuGet Packages dialog, click Restore in order to download missing packages.
    3. Finally, build the solution by clicking Build | Build Solution.

    [!NOTE] One of the advantages of using NuGet is that you don’t have to ship all the libraries in your project, reducing the project size. With NuGet Power Tools, by specifying the package versions in the Packages.config file, you will be able to download all the required libraries the first time you run the project. This is why you will have to run these steps after you open an existing solution from this lab.

  2. Open StoreManagerController class. To do this, expand the Controllers folder and double-click StoreManagerController.cs.
  3. The Delete controller action is exactly the same as the previous Store Details controller action: it queries the album object from the database using the id provided in the URL and returns the appropriate View. To do this, replace the HTTP-GET Delete action method code with the following:

    (Code Snippet - ASP.NET MVC 4 Helpers and Forms and Validation - Ex5 Handling Deletion HTTP-GET Delete action)

    [!code-csharpMain]
       1:  //
       2:  // GET: /StoreManager/Delete/5
       3:   
       4:  public ActionResult Delete(int id)
       5:  {
       6:       Album album = this.db.Albums.Find(id);
       7:   
       8:       if (album == null)
       9:       {
      10:            return this.HttpNotFound();
      11:       }
      12:   
      13:       return this.View(album);
      14:  }
  4. Right-click inside the Delete action method and select Add View. This will bring up the Add View dialog.
  5. In the Add View dialog, verify that the View name is Delete. Select the Create a strongly-typed view option and select Album (MvcMusicStore.Models) from the Model class drop-down. Select Delete from the Scaffold template drop-down. Leave the other fields with their default value and then click Add.

    Adding a Delete View
    Adding a Delete View
    Adding a Delete View
  6. The Delete template shows all the fields from the model. You will show only the album’s title. To do this, replace the content of the view with the following code:

    [!code-cshtmlMain]

       1:  @model MvcMusicStore.Models.Album
       2:  @{
       3:       ViewBag.Title = "Delete";
       4:  }
       5:  <h2>Delete Confirmation</h2>
       6:   
       7:  <h3> Are you sure you want to delete the album title <strong>@Model.Title </strong> ? </h3>
       8:   
       9:  @using (Html.BeginForm()) {
      10:       <p>
      11:            <input type="submit" value="Delete" /> |
      12:            @Html.ActionLink("Back to List", "Index")
      13:       </p>
      14:  }

#### Task 2 - Running the Application

In this task, you will test that the StoreManager Delete View page displays a confirmation deletion form.

  1. Press F5 to run the Application.
  2. The project starts in the Home page. Change the URL to /StoreManager. Select one album to delete by clicking Delete and verify that the new view is uploaded.

    Deleting an Album
    Deleting an Album

    Deleting an Album

#### Task 3- Implementing the HTTP-POST Delete Action Method

In this task, you will implement the HTTP-POST version of the Delete action method that will be invoked when a user clicks the Delete button. The method should delete the album in the database.

  1. Close the browser if needed, to return to the Visual Studio window. Open StoreManagerController class. To do this, expand the Controllers folder and double-click StoreManagerController.cs.
  2. Replace HTTP-POST Delete action method code with the following:

    (Code Snippet - ASP.NET MVC 4 Helpers and Forms and Validation - Ex5 Handling Deletion HTTP-POST Delete action)

    [!code-csharpMain]

       1:  //
       2:  // POST: /StoreManager/Delete/5
       3:   
       4:  [HttpPost]
       5:  public ActionResult Delete(int id, FormCollection collection)
       6:  {
       7:       Album album = this.db.Albums.Find(id);
       8:       this.db.Albums.Remove(album);
       9:       this.db.SaveChanges();
      10:   
      11:       return this.RedirectToAction("Index"); 
      12:  }

#### Task 4 - Running the Application

In this task, you will test that the StoreManager Delete View page lets you delete an Album and then redirects to the StoreManager Index View.

  1. Press F5 to run the Application.
  2. The project starts in the Home page. Change the URL to /StoreManager. Select one album to delete by clicking Delete. Confirm the deletion by clicking Delete button:

    Deleting an Album
    Deleting an Album
    Deleting an Album
  3. Verify that the album was deleted since it does not appear in the Index page.

### Exercise 6: Adding Validation

Currently, the Create and Edit forms you have in place do not perform any kind of validation. If the user leaves a required field blank or type letters in the price field, the first error you will get will be from the database.

You can add validation to the application by adding Data Annotations to your model class. Data Annotations allow describing the rules you want applied to your model properties, and ASP.NET MVC will take care of enforcing and displaying appropriate message to users.

#### Task 1 - Adding Data Annotations

In this task, you will add Data Annotations to the Album Model that will make the Create and Edit page display validation messages when appropriate.

For a simple Model class, adding a Data Annotation is just handled by adding a using statement for System.ComponentModel.DataAnnotation, then placing a [Required] attribute on the appropriate properties. The following example would make the Name property a required field in the View.

[!code-csharpMain]

   1:  using System.ComponentModel.DataAnnotations;
   2:  namespace SuperheroSample.Models
   3:  {
   4:      public class Superhero
   5:      {
   6:          [Required]
   7:          public string Name { get; set; }
   8:   
   9:          public bool WearsCape { get; set; }
  10:      }
  11:  }

This is a little more complex in cases like this application where the Entity Data Model is generated. If you added Data Annotations directly to the model classes, they would be overwritten if you update the model from the database. Instead, you can make use of metadata partial classes which will exist to hold the annotations and are associated with the model classes using the [MetadataType] attribute.

  1. Open the Begin solution located at Source/Ex6-AddingValidation/Begin/ folder. Otherwise, you might continue using the End solution obtained by completing the previous exercise.

    1. If you opened the provided Begin solution, you will need to download some missing NuGet packages before continue. To do this, click the Project menu and select Manage NuGet Packages.
    2. In the Manage NuGet Packages dialog, click Restore in order to download missing packages.
    3. Finally, build the solution by clicking Build | Build Solution.

    [!NOTE] One of the advantages of using NuGet is that you don’t have to ship all the libraries in your project, reducing the project size. With NuGet Power Tools, by specifying the package versions in the Packages.config file, you will be able to download all the required libraries the first time you run the project. This is why you will have to run these steps after you open an existing solution from this lab.

  2. Open the Album.cs from the Models folder.
  3. Replace Album.cs content with the highlighted code, so that it looks like the following:

    [!NOTE] The line [DisplayFormat(ConvertEmptyStringToNull=false)] indicates that empty strings from the model won’t be converted to null when the data field is updated in the data source. This setting will avoid an exception when the Entity Framework assigns null values to the model before Data Annotation validates the fields.

    (Code Snippet - ASP.NET MVC 4 Helpers and Forms and Validation - Ex6 Album metadata partial class)

    [!code-csharpMain]

       1:  namespace MvcMusicStore.Models
       2:  {
       3:      using System.ComponentModel;
       4:      using System.ComponentModel.DataAnnotations;
       5:   
       6:      public class Album
       7:      {
       8:          [ScaffoldColumn(false)]
       9:          public int AlbumId { get; set; }
      10:   
      11:          [DisplayName("Genre")]
      12:          public int GenreId { get; set; }
      13:   
      14:          [DisplayName("Artist")]
      15:          public int ArtistId { get; set; }
      16:   
      17:          [Required(ErrorMessage = "An Album Title is required")]
      18:          [DisplayFormat(ConvertEmptyStringToNull = false)]
      19:          [StringLength(160, MinimumLength = 2)]
      20:          public string Title { get; set; }
      21:   
      22:          [Range(0.01, 100.00, ErrorMessage = "Price must be between 0.01 and 100.00")]
      23:          [DataType(DataType.Currency)]
      24:          public decimal Price { get; set; }
      25:   
      26:          [DisplayName("Album Art URL")]
      27:          [DataType(DataType.ImageUrl)]
      28:          [StringLength(1024)]
      29:          public string AlbumArtUrl { get; set; }
      30:   
      31:          public virtual Genre Genre { get; set; }
      32:   
      33:          public virtual Artist Artist { get; set; }
      34:      }
      35:  }

    [!NOTE] This Album partial class has a MetadataType attribute which points to the AlbumMetaData class for the Data Annotations. These are some of the Data Annotation attributes you are using to annotate the Album model:

    • Required - Indicates that the property is a required field
    • DisplayName - Defines the text to be used on form fields and validation messages
    • DisplayFormat - Specifies how data fields are displayed and formatted.
    • StringLength - Defines a maximum length for a string field
    • Range - Gives a maximum and minimum value for a numeric field
    • ScaffoldColumn - Allows hiding fields from editor forms

#### Task 2 - Running the Application

In this task, you will test that the Create and Edit pages validate fields, using the display names chosen in the last task.

  1. Press F5 to run the Application.
  2. The project starts in the Home page. Change the URL to /StoreManager/Create. Verify that the display names match the ones in the partial class (like Album Art URL instead of AlbumArtUrl)
  3. Click Create, without filling the form. Verify that you get the corresponding validation messages.

    Validated fields in the Create page
    Validated fields in the Create page
    Validated fields in the Create page
  4. You can verify that the same occurs with the Edit page. Change the URL to /StoreManager/Edit/1 and verify that the display names match the ones in the partial class (like Album Art URL instead of AlbumArtUrl). Empty the Title and Price fields and click Save. Verify that you get the corresponding validation messages.

    Validated fields in the Edit page
    Validated fields in the Edit page

    Validated fields in the Edit page

### Exercise 7: Using Unobtrusive jQuery at Client Side

In this exercise, you will learn how to enable MVC 4 Unobtrusive jQuery validation at client side.

[!NOTE] The Unobtrusive jQuery uses data-ajax prefix JavaScript to invoke action methods on the server rather than intrusively emitting inline client scripts.

#### Task 1 - Running the Application before Enabling Unobtrusive jQuery

In this task, you will run the application before including jQuery in order to compare both validation models.

  1. Open the Begin solution located at Source/Ex7-UnobtrusivejQueryValidation/Begin/ folder. Otherwise, you might continue using the End solution obtained by completing the previous exercise.

    1. If you opened the provided Begin solution, you will need to download some missing NuGet packages before continue. To do this, click the Project menu and select Manage NuGet Packages.
    2. In the Manage NuGet Packages dialog, click Restore in order to download missing packages.
    3. Finally, build the solution by clicking Build | Build Solution.

    [!NOTE] One of the advantages of using NuGet is that you don’t have to ship all the libraries in your project, reducing the project size. With NuGet Power Tools, by specifying the package versions in the Packages.config file, you will be able to download all the required libraries the first time you run the project. This is why you will have to run these steps after you open an existing solution from this lab.

  2. Press F5 to run the application.
  3. The project starts in the Home page. Browse /StoreManager/Create and click Create without filling the form to verify that you get validation messages:

    Client validation disabled
    Client validation disabled
    Client validation disabled
  4. In the browser, open the HTML source code:

    [!code-htmlMain]

       1:  ...
       2:            <div class="editor-label">
       3:                  <label for="Price">Price</label>
       4:            </div>
       5:            <div class="editor-field">
       6:                  <input class="text-box single-line" id="Price" name="Price" type="text" value="" />
       7:                  <span class="field-validation-valid" id="Price_validationMessage"></span>
       8:            </div>
       9:   
      10:            <div class="editor-label">
      11:                  <label for="AlbumArtUrl">Album Art URL</label>
      12:            </div>
      13:            <div class="editor-field">
      14:                  <input class="text-box single-line" id="AlbumArtUrl" name="AlbumArtUrl" type="text" value="" />
      15:                  <span class="field-validation-valid" id="AlbumArtUrl_validationMessage"></span>
      16:            </div>
      17:   
      18:            <p>
      19:                  <input type="submit" value="Create" />
      20:            </p>
      21:       </fieldset>
      22:  </form><script type="text/javascript">
      23:  //<![CDATA[
      24:  if (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; }
      25:  window.mvcClientValidationMetadata.push({"Fields":[{"FieldName":"GenreId","ReplaceValidationMessageContents":true,"ValidationMessageId":"GenreId_validationMessage","ValidationRules":[{"ErrorMessage":"The Genre field is required.","ValidationParameters":{},"ValidationType":"required"},{"ErrorMessage":"The field Genre must be a number.","ValidationParameters":{},"ValidationType":"number"}]},{"FieldName":"ArtistId","ReplaceValidationMessageContents":true,"ValidationMessageId":"ArtistId_validationMessage","ValidationRules":[{"ErrorMessage":"The Artist field is required.","ValidationParameters":{},"ValidationType":"required"},{"ErrorMessage":"The field Artist must be a number.","ValidationParameters":{},"ValidationType":"number"}]},{"FieldName":"Title","ReplaceValidationMessageContents":true,"ValidationMessageId":"Title_validationMessage","ValidationRules":[{"ErrorMessage":"An Album Title is required","ValidationParameters":{},"ValidationType":"required"},{"ErrorMessage":"The field Title must be a string with a minimum length of 2 and a maximum length of 160.","ValidationParameters":{"min":2,"max":160},"ValidationType":"length"}]},{"FieldName":"Price","ReplaceValidationMessageContents":true,"ValidationMessageId":"Price_validationMessage","ValidationRules":[{"ErrorMessage":"Price must be between 0.01 and 100.00","ValidationParameters":{"min":0.01,"max":100},"ValidationType":"range"},{"ErrorMessage":"Price is required","ValidationParameters":{},"ValidationType":"required"},{"ErrorMessage":"The field Price must be a number.","ValidationParameters":{},"ValidationType":"number"}]},{"FieldName":"AlbumArtUrl","ReplaceValidationMessageContents":true,"ValidationMessageId":"AlbumArtUrl_validationMessage","ValidationRules":[{"ErrorMessage":"The field Album Art URL must be a string with a maximum length of 1024.","ValidationParameters":{"max":1024},"ValidationType":"length"}]}],"FormId":"form0","ReplaceValidationSummary":false,"ValidationSummaryId":"validationSummary"});
      26:  //]]>
      27:  </script>
      28:  ...

#### Task 2 - Enabling Unobtrusive Client Validation

In this task, you will enable jQuery unobtrusive client validation from Web.config file, which is by default set to false in all new ASP.NET MVC 4 projects. Additionally, you will add the necessary scripts references to make jQuery Unobtrusive Client Validation work.

  1. Open Web.Config file at project root, and make sure that the ClientValidationEnabled and UnobtrusiveJavaScriptEnabled keys values are set to true.

    [!code-xmlMain]

       1:  ...
       2:  <configuration>
       3:    <appSettings>
       4:       <add key="webpages:Version" value="2.0.0.0" />
       5:       <add key="webpages:Enabled" value="false" />
       6:       <add key="PreserveLoginUrl" value="true" />
       7:       <add key="ClientValidationEnabled" value="true" />
       8:       <add key="UnobtrusiveJavaScriptEnabled" value="true" />
       9:  </appSettings>
      10:  ...

    [!NOTE] You can also enable client validation by code at Global.asax.cs to get the same results:

    HtmlHelper.ClientValidationEnabled = true;

    Additionally, you can assign ClientValidationEnabled attribute into any controller to have a custom behavior.

  2. Open Create.cshtml at **Views*.
  3. Make sure the following script files, jquery.validate and jquery.validate.unobtrusive, are referenced in the view throught the “~/bundles/jqueryval” bundle.

    [!code-cshtmlMain]

       1:  ...
       2:  @section Scripts {
       3:       @Scripts.Render("~/bundles/jqueryval")
       4:  }

    [!NOTE] All these jQuery libraries are included in MVC 4 new projects. You can find more libraries in the /Scripts folder of you project.

    In order to make this validation libraries work, you need to add a reference to the jQuery framework library. Since this reference is already added in the _Layout.cshtml file, you do not need to add it in this particular view.

#### Task 3 - Running the Application Using Unobtrusive jQuery Validation

In this task, you will test that the StoreManager create view template performs client side validation using jQuery libraries when the user creates a new album.

  1. Press F5 to run the application.
  2. The project starts in the Home page. Browse /StoreManager/Create and click Create without filling the form to verify that you get validation messages:

    Client validation with jQuery enabled
    Client validation with jQuery enabled
    Client validation with jQuery enabled
  3. In the browser, open the source code for Create view:

    [!code-htmlMain]

       1:  ...
       2:  <div class="editor-label">
       3:      <label for="Title">Title</label>
       4:  </div>
       5:  <div class="editor-field">
       6:      <input class="text-box single-line" data-val="true" data-val-length="The field Title must be a string with a minimum length of 2 and a maximum length of 160." data-val-length-max="160" data-val-length-min="2" data-val-required="An Album Title is required" id="Title" name="Title" type="text" value="" />
       7:      <span class="field-validation-valid" data-valmsg-for="Title" data-valmsg-replace="true"></span>
       8:  </div>
       9:   
      10:  <div class="editor-label">
      11:      <label for="Price">Price</label>
      12:  </div>
      13:  <div class="editor-field">
      14:      <input class="text-box single-line" data-val="true" data-val-number="The field Price must be a number." data-val-range="Price must be between 0.01 and 100.00" data-val-range-max="100" data-val-range-min="0.01" data-val-required="Price is required" id="Price" name="Price" type="text" value="" />
      15:      <span class="field-validation-valid" data-valmsg-for="Price" data-valmsg-replace="true"></span>
      16:  </div>
      17:   
      18:  <div class="editor-label">
      19:      <label for="AlbumArtUrl">Album Art URL</label>
      20:  </div>
      21:  <div class="editor-field">
      22:      <input class="text-box single-line" data-val="true" data-val-length="The field Album Art URL must be a string with a maximum length of 1024." data-val-length-max="1024" id="AlbumArtUrl" name="AlbumArtUrl" type="text" value="" />
      23:      <span class="field-validation-valid" data-valmsg-for="AlbumArtUrl" data-valmsg-replace="true"></span>
      24:  </div>        
      25:  ...

    [!NOTE] For each client validation rule, Unobtrusive jQuery adds an attribute with data-val-rulename=“message”. Below is a list of tags that Unobtrusive jQuery inserts into the html input field to perform client validation:

    • Data-val
    • Data-val-number
    • Data-val-range
    • Data-val-range-min / Data-val-range-max
    • Data-val-required
    • Data-val-length
    • Data-val-length-max / Data-val-length-min

    All the data values are filled with model Data Annotation. Then, all the logic that works at server side can be run at client side. For example, Price attribute has the following data annotation in the model:

    [!code-csharpMain]

       1:  [Required(ErrorMessage = "Price is required")]
       2:  [Range(0.01, 100.00, ErrorMessage = "Price must be between 0.01 and 100.00")]
       3:  public object Price { get; set; }

    After using Unobtrusive jQuery, the generated code is:

    [!code-htmlMain]

       1:  <input data-val="true"
       2:  data-val-number="The field Price must be a number."
       3:  data-val-range="Price must be between 0.01 and 100.00"
       4:  data-val-range-max="100"
       5:  data-val-range-min="0.01"
       6:  data-val-required="Price is required"
       7:  id="Album_Price" name="Album.Price" type="text" value="0" />


## Summary

By completing this Hands-On Lab you have learned how to enable users to change the data stored in the database with the use of the following:

## Appendix A: Installing Visual Studio Express 2012 for Web

You can install Microsoft Visual Studio Express 2012 for Web or another “Express” version using the Microsoft Web Platform Installer. The following instructions guide you through the steps required to install Visual studio Express 2012 for Web using Microsoft Web Platform Installer.

  1. Go to [https://go.microsoft.com/?linkid=9810169](https://go.microsoft.com/?linkid=9810169). Alternatively, if you already have installed Web Platform Installer, you can open it and search for the product “Visual Studio Express 2012 for Web with Windows Azure SDK”.
  2. Click on Install Now. If you do not have Web Platform Installer you will be redirected to download and install it first.
  3. Once Web Platform Installer is open, click Install to start the setup.

    Install Visual Studio Express
    Install Visual Studio Express
    Install Visual Studio Express
  4. Read all the products’ licenses and terms and click I Accept to continue.

    Accepting the license terms
    Accepting the license terms
    Accepting the license terms
  5. Wait until the downloading and installation process completes.

    Installation progress
    Installation progress
    Installation progress
  6. When the installation completes, click Finish.

    Installation completed
    Installation completed
    Installation completed
  7. Click Exit to close Web Platform Installer.
  8. To open Visual Studio Express for Web, go to the Start screen and start writing “VS Express”, then click on the VS Express for Web tile.

    VS Express for Web tile
    VS Express for Web tile

    VS Express for Web tile

## Appendix B: Using Code Snippets

With code snippets, you have all the code you need at your fingertips. The lab document will tell you exactly when you can use them, as shown in the following figure.

Using Visual Studio code snippets to insert code into your project
Using Visual Studio code snippets to insert code into your project

Using Visual Studio code snippets to insert code into your project

To add a code snippet using the keyboard (C# only)

  1. Place the cursor where you would like to insert the code.
  2. Start typing the snippet name (without spaces or hyphens).
  3. Watch as IntelliSense displays matching snippets’ names.
  4. Select the correct snippet (or keep typing until the entire snippet’s name is selected).
  5. Press the Tab key twice to insert the snippet at the cursor location.
Start typing the snippet name
Start typing the snippet name

Start typing the snippet name

Press Tab to select the highlighted snippet
Press Tab to select the highlighted snippet

Press Tab to select the highlighted snippet

Press Tab again and the snippet will expand
Press Tab again and the snippet will expand

Press Tab again and the snippet will expand

To add a code snippet using the mouse (C#, Visual Basic and XML) 1. Right-click where you want to insert the code snippet.

  1. Select Insert Snippet followed by My Code Snippets.
  2. Pick the relevant snippet from the list, by clicking on it.
Right-click where you want to insert the code snippet and select Insert Snippet
Right-click where you want to insert the code snippet and select Insert Snippet

Right-click where you want to insert the code snippet and select Insert Snippet

Pick the relevant snippet from the list, by clicking on it
Pick the relevant snippet from the list, by clicking on it

Pick the relevant snippet from the list, by clicking on it



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-helpers-forms-and-validation.htm
< THANKS ME>