Syllabus Schedule Project Labs Canvas Server Access CSS Tutorial Assignment 1 Assignment 2 Assignment 3 Assignment 4 Assignment 5 Assignment 6 Assignment 7 Assignment 8 Assignment 9

Assignment 5 - Putting it all together

These exercises utilize all of the tools that the course has covered so far: models, views, controller, DataRepositoty, Sql Server database, layout views, and partial views. It is also a template for the first part of the MusicStore project.

Visual Studio Tip: This answer explains how to exclude your web.config file from being published to the server. Sql Server requires different connection strings in Visual Studio and on the server. To avoid inadvertently publishing incorrect connection string to the server (and breaking your server applications) you can exclude web.config from being automatically published with your project. To publish web.config right click on the file and select "Publish web.config."  
  1. Bird - This exercise displays four random bird images. It uses a BirdModel, controller, dataRepository, sql server database, layout view, and view. Steps:
    1. Photos: .NET MVC will only serve site content, such as images and css, from the content folder. In the content folder add a subfolder named Images and another subfolder named birds.  Images for the six birds are in Unzip the images and drag them into your VS solution. (Content added via Windows explorer cannot be seen in Visual Studio.) Note that there are two versions of each photo, a full size and a thumb.
    2. Model: Create a model named BirdModel with four string properties: Id, Name, ImageName, Description.
    3. Database: Create a Sql Server database named Birds with a table named BirdDetails. Add the following fields and make Id an autonumber field (see A04 if you need a refresher on how to do this).
      birds database
    4. Populate the database for the six birds by copying and pasting the text from the sample (see the last exercise for the description text or just add random text). Include the file extensions in the images names (ie: finch.jpg).
    5. DataRepository: Copy PeopleCrudRepositoy and rename it BirdRepository. Change the connection string name to "Birds"  This exercise only reads data so you can delete all of the methods except GetAllPeople() and  GetOnePerson(int Id).
    6. The index page displays four birds randomly selected from the database. Rename GetAllPeople() to GetRandom(). This shows the syntax for a sql statement that selects n random records. Modify the sql to select 4 random records.  Also change the model from PersonModel to BirdModel. Tip: If you are unsure about the sql try writing and executing it in Visual Studio. Right-click on the Bird database and select "New query." The designer provides IntelliSense and underlines syntax errors.  Writing the sql this way isolates sql problems from other application problems.
    7. The detail page displays one bird. Rename GetOnePerson(int id) to GetOneBird(int id) and make the other needed modifications.
    8. Web.config: Copy the two connection strings for "People" and rename them "Birds." Note that two changes are needed to each string.
    9. Controller: Create a new empty controller named "BirdController."  Add using statements pointing to your Models and DataRepository.
    10. Create an object for accessing BirdRepositoy. See PeopleController for example.
    11. The index method sends a List of four random birds to the view. See the Index method of PeopleController for syntax.
    12. View: Add a view for index using the List template and BirdModel model. Test it. You should see a table containing the names of four random birds.
    13. We want to display images, not image names. For the browser to find an image it needs the path from the web server's root folder. We know the path within our application but that path above our application can change. For instance, compare the two paths:


      The solution is to use the Razor Href() extension, like so:

      Href("~/content/images/birds/" + thumbImage)

      It replaces the ~ tilde with the path to the server root folder. The index page displays the thumbnail sized photos which are named with a "T" just before the dot. The following code snippet add the "T" to the name and displays the images. Put it in index.cshtml:
      <div class="row">
          @foreach (var item in Model)
              <div class="col-md-6 ">
                  <div class="thumbContainer">
                      @{string thumbImage = item.ImageName.Replace(".", "T.");}
                      @* Href() replaces the tilde (~) with the path to the server root folder *@
                      @{string path = Href("~/content/images/birds/" + thumbImage);}
                      <img src= '@path' class='birdThumb' alt="@item.Name" title="@item.Name" />
    14. Layout: The next step is to improve the styling with a custom layout. Currently the page is using the default layout in Views/Shared/_Layout.cshtml.  Copy this layout into Views/Bird. Also copy _ViewStart.cshtml to the Bird folder and edit its Layout tag to point to the Bird folder.
    15. Test to make sure that you are using the _Layout view in Bird folder. The easiest way to do this is to put some text into the layout page and refresh the browser.  The text should appear in the view.
    16. CSS: Our custom site needs a custom style sheet. From the sample site copy both the css <link> tag from index.cshtml (browser "view source"). Create a new css file named bird.css, place it in the "Content" folder, and add the CSS from the sample site.
    17. Test your site. It should look similar to the sample site.
  2. BirdColors - This exercise builds upon Bird by adding bird color categories. Steps: colors table
    1. Database - The database will need two new tables: colors and birdColors. Colors contains the color names and birdColors associates birds and colors. Create a table named Colors and add the data shown in the image. ColorID is the primary key.
    2. Create a second table named birdColors. The primary key is a composite key of colorID and Id (from BirdDetails table). (How to set a composite primary key). Add at least ten records associating bird Id with colorId (a bird with three colors will have three records in birdColors).
    3. Controller - Create an new action method named BirdColors. This page will have the same content as index so copy both the controller and view from index.
    4. Layout View: The class handout "Partial Views" may be helpful for this part. The page needs a two column layout, left column for search and browse and the main content area. Copy _Layout.cshtml from the bird folder and rename it _2ColLayout.cshtml.
    5. _2ColLayout.cshtml contains the HTML for the navigation menu at the top of the page. Tidy up the layout by moving the this code into a partial View. Right-click on Bird view -> Add -> new item... -> Mvc 5 Partial Page. Name it "_header.cshtml" and paste in the code for the navigation menu. If you are unsure which HTML to move look at the source code of the sample. It contains comments that will help.  Add @Html.Partial("_header") to the layout.
    6. BirdColors needs to use the 2 column layout page. Add just below the ViewBag tag:

      Layout = "~/Views/Bird/_2ColLayout.cshtml";

    7. Test that the new layout is being used by adding some random text to the layout and viewing BirdColors.cshtml in the browser.
    8. 2-column layout: Use Bootstrap to create a 2 column layout. Make the left column 3-Bootstrap columns and the main content area 9-Bootstrap columns. If you are unsure how to do this look at the source code for the sample. Move the RenderBody() tag into the main content area, put some random text into the left menu, and view in browser to test.
    9. ColorModel: The next step is to populate a list of color names for the left menu. Create a new model named ColorModel with two properties: colorId and Name. This model can be defined in the same file as BirdModel.
    10. DataRepositoy needs a method that gets a List of color names. The repository contains a method named GetRandom() that return a list. Copy it, rename it GetColors(), and modify the sql to get color names and Ids sorted by color name.
    11. Controller: The left menu will need an action method that queries the database and passes the data to the left partial view. Create a new Action Method named _leftMenu and have it return a list of color names.
    12. Partial View: Right-click on the new action method and create a new View: Template is List, model is ColorModel, check "create as a partial view."
    13. The partial view should not use a layout since its parent page has one. Disable the layout with:
           Layout = null;              
    14. The default List view uses a table and a foreach loop. The menu needs only an unordered list with ActionLinks. The foreach loop:
       @foreach (var color in Model)
               @Html.ActionLink(color.Name, "ShowColor", new { Id = color.ColorId })
    15. Call _leftMen into the layout the Html.Action helper. This will call the _leftMenu action method in the controller.


    16. You may copy the formatting from the sample or create your own.
    17. The partial view _leftMenu has its own Action Method in the controller and does not depend upon the pages where it is rendered. It can even be called outside of a parent page. If this behavior is not wanted the controller can be decorated with the attribute [ChildActionOnly].
    18. Test BirdColors.
    19. Now that the menu is complete we need a page that displays birds by color. Add a new method to BridRepository named GetByColor(string colorID) that retrieves birds by colorID:
         string sql = "select, d.Name, d.ImageName " +
        " from BirdDetails d, birdColors c " +
        " where d.Id = c.Id " +
        " and c.colorID = @colorID " +
        " order by d.Name";
         List<BirdModel> birds = db.Query<BirdModel>(sql, new { colorID }).ToList();
         return birds;                        
    20. The page that displays birds of a given color has the same layout as BirdColors (two columns of bird Thumbnails) so we can reuse the same View. Create a new controller named "ShowColor." It gets the list of birds and redirects to "BirdColors" view.

      return View("BirdColors", br.GetByColorId(id));

    21.  Test by clicking on some colors.
    22. Navigation: User's need a way to return to the home page (BirdColors). Add the following near the bottom of the left menu:
          <p class="text-center">
              <br />
              @Html.ActionLink("Home", "BirdColors")
    23. Test!
  3. BirdDetail - This page displays a single item with all relevant details. Steps:
    1. DataRepository - Add a method GetOneBird(int Id) that returns BirdModel.
    2. Controller - Add a controller named BirdDetails. Add the appropriate code to populate BirdModel.
    3. View - Create a view. You may use the CSS from the sample or create your own. Syntax for the image tag:
       @* Href() replaces the tilde (~) with the path to the server root folder *@
       @{string path = Href("~/content/images/birds/" + Model.ImageName);}
       <img src='@path' class='birdImage' alt="@Model.Name" title="@Model.Name" />
    4. ImageLinks - User's navigate to BirdDetail by clinking on an image in BirdColors. Wrap the image tag in BirdColors with an anchor tag.
        <a href='@Url.Action("BirdDetail/" + item.Id , "Bird")'>
             <img src= '@path' class='birdThumb' alt="@item.Name" title="@item.Name" />
    5. Also add a details link to BirdColors. Syntax is similar to image except put text inside the anchor tag.
    6. Test!

Submission instructions: Submit assignments via the Canvas course management system. Submit the full URL for each exercise in the assignment, listing the URLs in the same order that they are listed in the assignment. To minimize typos in URLs it is strongly recommended that you copy the URLs from the address bar of the browser rather than trying to type them. Incorrect URLs will not be graded and no credit will be given.

When pages are connected via navigation (as in your music store project) it is only necessary to submit the URL of the first page.

Regular Expressions HTML Color Names Color Picker ASCII Character Codes Unicode Character Codes