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 to 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. Start Microsoft Visual Web Developer 2010 Express from Start | All Programs | Microsoft Visual Studio 2010 Express | Microsoft Visual Web Developer 2010 Express.
  2. In the File menu, choose Open Project. In the Open Project dialog, browse to Source\Ex04-AddingACreateView\Begin, select MvcMusicStore.sln and click Open.
  3. Open StoreManagerController class. To do this, expand the Controllers folder and double-click StoreManagerController.[cs|vb].
  4. Replace the Create action method code with the following:

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

    C#

            //
    FakePre-953c910df6814a23b117e8a1bb1b6994-74a8fe80aab445839a0998ff974c43a4FakePre-89d474cbfe224523b7406ba81717c1ca-9753a8d899e349219f533ef5a7ad02b3FakePre-5ee2d1afd04642a3ae5799f058d369fa-373330e20a234d428f760deabf3dddaeFakePre-af52f2b440dd45ff8b75ee8c65bc2c46-9886104253f34f2e989a4a39f91aaf21 var viewModel = new StoreManagerViewModel() { Album = new Album(), Genres = new SelectList(storeDB.Genres.ToList(), "GenreId", "Name"), Artists = new SelectList(storeDB.Artists.ToList(), "ArtistId", "Name") }; return View(viewModel);FakePre-a8df6b6a3f9a4ac2bedd02bef63ee101-f91caa2d40b54191b8a6f0d8bdacb1bfFakePre-22986349a09d4a7fa0e51d2f152fc546-e44cd1436504408dae152028b57a1d88

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

    Visual Basic

        '
    FakePre-185f4e69b5ff4510aa50c3d6001c9c13-98a37ac41f0b48c488b3d36063251c56FakePre-fc7e3ef80d794eb1b8427eeff067805d-dad161431fe4439b9b2ad4868bbb0e03FakePre-c5d55bd20b9b4afb8de68fa2eb8ea30b-295703d0f30f4e32bf65796bab397461FakePre-0b36bf9bf1c74983bc0bc4e11b99f170-365144b0caf44678ab3e812e3fcead95 Dim viewModel = New StoreManagerViewModel With {.Album = New Album, .Genres = New SelectList(storeDB.Genres.ToList(), "GenreId", "Name"), .Artists = New SelectList(storeDB.Artists.ToList(), "ArtistId", "Name")} Return View(viewModel) FakePre-cfb07b1cb7a94111bdf7890ad93ebcbc-80c88cf8fa284824a822254124e9dd99FakePre-eac84854261643dcb667df1cd2386f41-27b00fd673a74379bdeab2a9daf7e0ca

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. Before creating the new View template, you should build the project so that the Add View Dialog knows about the class to use. Build the project by selecting the Debug menu item and then Build MvcMusicStore.

    Figure 24

    Building the project

  2. Right-click inside the Create action method and select Add View. This will bring up the Add View dialog.
  3. In the Add View dialog, verify that the View Name is Create. Check the Create a strongly-typed view checkbox and select StoreManagerViewModel (MvcMusicStore.ViewModels) from the View data class drop-down. Select Create from the View content drop-down. Leave the other fields with their default value and then click Add.

    Figure 25

    Adding an Edit View

  4. Update the generated View template to invoke the Html.EditorFor() helper method:

    HTML(C#)

    FakePre-c5f6ca62af174c3786d62284a33c029c-b5bb09f4fb0b4465ac6458d6f1fb4566FakePre-4e856f9113294601a0c75786bce0659b-975e8f148afb4bd1b87cc4d4bdb19bf7FakePre-84eb7da80d9649f88b5848404a58a32a-70135049498742469b8b42c3b17aef00FakePre-b79c97bb6768447292ec19cd39d40196-d5b6ceadbe754979a91847e7590ffd3c <legend>Create Album</legend> <%: Html.EditorFor(model => model.Album, new { Artists = Model.Artists, Genres = Model.Genres })%> <p> <input type="submit" value="Save" /> </p>FakePre-ad4549efe2754002b8159dedf9f41f46-d7a5fb1fd0e94656991f3b25f96ba34cFakePre-38df421600a3497ca9e42d643f1e1632-d23598ab891a4ac5a4756283be6c51b6FakePre-c66f802d16ab45f3a6dcf56ed7750f68-efeaa640fcad440cb3fbbdc82be41659
    

    <% Using Html.BeginForm() %>
    FakePre-d3f9b7ba4f1948e3b92ff07419bd2a4b-4404c8048e2c4e7185c20abbe9060a12FakePre-2df987b6eeed4a07b3931ffaaea1ad6f-ae58f18c185743468c8f499c2af7dedeFakePre-f72842b2b8064f049637e24fb5670a0e-c1b2679b87cf45cbbf40d9276f0c17db <legend>Create Album</legend> <%: Html.EditorFor(Function(model) model.Album, New With {Key .Artists = Model.Artists, Key .Genres = Model.Genres})%> <p> <input type="submit" value="Save" /> </p>FakePre-aa2db85ee37948f1ae650e32a95c9ac0-02da65b6e698438ebac76dd49ee3ab54FakePre-a76df5349b4d44c4915b6730361af845-f58c75250b4c46668e31f591127ed45dFakePre-47dfa6a4689c4984a04e2d2bb66636ab-fc65dfc6a4a945e68acde27ebb0c7a71

Task 3 – Running the Application

In this task, you will test that the StoreManagerCreate 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.

    Figure 26

    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|vb].
  2. Replace HTTP-POST Create action method code with the following:

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

    C#

            //
    FakePre-212e1ded554647699e3b2cdb463bfa4f-9ba2fa15e6004cbe98c47f448a8a7430FakePre-e0213c83c00c41c8be8a2a8ab1981ae2-9221043c46da44eb8ff7fe7c789f94acFakePre-47eff3c6951748caa71bc71b143de4d3-dbb34610bfe24b85916660a55ab0a800 public ActionResult Create(Album album) { try { if (ModelState.IsValid) { // Save Album storeDB.AddToAlbums(album); storeDB.SaveChanges(); return Redirect("Index"); } } catch (Exception ex) { ModelState.AddModelError(String.Empty, ex); } // Invalid - redisplay with errors var viewModel = new StoreManagerViewModel() { Album = album, Genres = new SelectList(storeDB.Genres.ToList(), "GenreId", "Name", album.GenreId), Artists = new SelectList(storeDB.Artists.ToList(), "ArtistId", "Name", album.ArtistId) }; return View(viewModel); }FakePre-0e610382e1724eb3ac94f8dbbae20c43-c72e8d33f0d141418eeebd8ffb97e1c8FakePre-f4a0b53424304db5b9e52942c5fac9bf-2cb91f1143ce4baea9ecb83cc0c8bf6eFakePre-8f112543ebe04d648b82c9cd0c3a14ea-522b661397c14cbca74b91d13233e7eeFakePre-28dc2a75a86b457080f3282c6c9ce9f1-2ed0c852e908445baec2b7a3ac91d3bf

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

    Visual Basic

        '
    FakePre-fcd03933b9df40e2a49a3340e9dc4e20-53bc5a49801e4264ad1b1062875714c1FakePre-995e3c5e76a649269adc27fd5f781ea9-07dde58fe6554d73b966f270db3d38f0FakePre-d8e20fefbb56417d8a0079b624b7a9e5-6355d2132ea04a41b16277bddbe3c548 Public Function Create(ByVal album As Album) As ActionResult Try If ModelState.IsValid Then 'Save Album storeDB.AddToAlbums(album) storeDB.SaveChanges() Return Redirect("Index") End If Catch ex As Exception ModelState.AddModelError(String.Empty, ex) End Try 'Invalid - redisplay with errors Dim viewModel = New StoreManagerViewModel With {.Album = album, .Genres = New SelectList(storeDB.Genres.ToList(), "GenreId", "Name", album.GenreId), .Artists = New SelectList(storeDB.Artists.ToList(), "ArtistId", "Name", album.ArtistId)} Return View(viewModel) End FunctionFakePre-a8f9ff96c1424a3285284d340a5c7ecb-b84419182d7344548bc222088ee894bfFakePre-43fa809f5c934ae4b6ec3d1c4153e676-78c8410412144ee3a352e467186ea273FakePre-d49746abbccb47f8aaec88dd07dcd3f1-170a0c5672294762adb6ee0c97bf0fb3FakePre-0bc47eeb4b0e4a33b06323f20404de7c-c06dec24f5e945118a4cb6c473923409

    Note:
    One difference from the previous Edit action method is that instead of loading an existing Album and calling UpdateModel, the action method is receiving an Album as a parameter. ASP.NET MVC will automatically create this Album object from the posted <form> values.

    The method checks that the submitted values are valid, and if they are, it saves the new Album in the database and then redirects to the StoreManager Index View.

Task 5 – Running the Application

In this task, you will test that the StoreManagerCreate 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 the empty form with data for a new Album, like the one in the following figure:

    Figure 27

    Creating an Album

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

    Figure 28

    New Album created

Next Step

Exercise 5: Handling Deletion