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 03 - Working with Web Forms

Visual Studio Tip: When adding new code files to a project it is best to create a new file using Visual Studio and paste the code into the file. Code files with Windows Explorer may be hidden in Visual Studio.

Non-code files, such as images, may be added to your project via Windows explorer. To see them in Visual Studio you must click the refresh icon.

  1. BigWebForm  - In this exercise you will modify the form view that is created by Visual Studio. As you saw in assignment 2 Visual Studio's "Add View..." wizard examines the data model generates views that include form elements, layout, and validation. The wizard can generate textboxes, checkboxes, labels and buttons but does not create radiobuttons, dropdown lists, or hidden fields. These form elements must be added manually.

    In this exercise you will add a dropdown list, radiobuttons, a hidden field to the class handout BigWebForm, which already contains a textbox, a textbox for dates, and a checkbox.  Steps:

    1. Model: Create a model named BigWebFormModel and add the following properties:
          public class BigWebFormModel
              [Display(Name = "First Name")]
              public string FName { get; set; } //textbox
              public string Gender { get; set; } // radioButtonList
              [Display(Name = "State")]
              public string StateAbbr { get; set; } //dropdown list
              public DateTime BirthDate { get; set; } //textbox
              [Display(Name = "Seahawk Fan?")]
              public bool IsSeaHawkFan { get; set; } //checkbox
              public int PersonId { get; set; } //hidden
    2. ViewModel: The drop-down list of state names needs to be populated with data. This data is called "view data" since it is used solely to populate the view. It is good MVC practice to store view data seperate from the model, typically in a folder named "ViewModel." Right-click on your projects root folder "Mis324Assignments" and add a new folder named "ViewModels". 
    3. One of the most straightforward ways to store the form data is in a static List. This StackOverFlow answer by Nagle explains how to use a static List to store view data. A static list is used because it can be called directly from the view without instantiating an object. Nagle's example uses c# collection initializer syntax to define and populate the class in a single statement. Add a new class to the ViewModel folder named ListStatesModel and add the following code:
      using System.Collections.Generic;
      namespace Mis324Assignments.ViewModels.ListStatesViewModel
          public class State
              public string StateName { get; set; }
              public string StateAbbr { get; set; }
          public static class ListStatesViewModel
              //populate list using object initializer syntax
              public static List<State> StateList = new List<State> {
                  new State () {StateName = "Alaska", StateAbbr = "AK"  },
                  new State () {StateName = "California", StateAbbr = "CA"  },
                  new State () {StateName = "Idaho", StateAbbr = "ID"  },            
                  new State () {StateName = "Montana", StateAbbr = "MT"  },
                  new State () {StateName = "Oregon", StateAbbr = "OR"  },            
                  new State () {StateName = "Washington", StateAbbr = "WA"  }
    4. Controller: Create a new Controller named BigWebFormController. Add [HttpGet] and [HttpPost] action handlers similar to the Person exercise in A02.
    5. Person ID would typically be generated by the database but we will assign it manually. In the [HttpGet] handler add the following:
                  Response.Write("Method Get <br>");
                  //set a couple of form values
                  BigWebFormModel bwf = new BigWebFormModel();
                  bwf.PersonId = 6;
                  bwf.IsSeaHawkFan = true;
                  return View(bwf);
    6. View: Create a view by right clicking in either of the two Action handlers and selecting "Add View..." View name is "Index" template is "Create" and Model class is BigWebFormModel. Also check "Reference script libraries." This will implement JavaScript validation rather than just server side validation.
    7. Test your project by opening the new view in a browser. You should see a view with five textboxes and a checkbox, corresponding to the properties in your model. Notice that the Html.EditorFor control displays textboxes for string properties and checkboxs for boolean properties.
    8. Replace the gender EditorFor control to two radiobuttons as shown in this RadioButtonFor tutorial. Add text to the right of the radio buttons indicating which is male and female. Test!
    9. Replace the PersonID EditorFor with a hidden field as shown in this HiddenFor tutorial . Also remove the label and validator controls for this element since they are not needed. Test.
    10. The next step is to change the state textbox to a dropdown list. The view will need to have access to the ViewModel. Add the following Using statement to the view:

      @using Mis324Assignments.ViewModels.ListStatesViewModel;

    11. Replace the Html.EditorFor state helper with the following Html helper.
                      @Html.DropDownListFor(m => m.StateAbbr,
                      new SelectList(ListStatesViewModel.StateList, "StateAbbr", "StateName"),
                      "Please enter your state of residence",
                      htmlAttributes: new { @class = "form-control" })
    12. The DropDown helper above contains four parameters:
      1. identifies model property being populated (StateAbbr)
      2. creates a new SelectList based upon the ViewModel. DropDown list controls use the SelectList class to describe the list options.
      3. Optional initial prompt in the dropdown list
      4. optional CSS class applied to the dropdown list
    13. Test to make sure the dropdown list is working.
    14. Controller:Use the ViewBag to display all of the model values similar to the Person exericse in A02.
    15. Your output should be similar to the working sample.
    16. Done! 
  2. FontPicker - This exercise uses a textbox to retrieve a message from the user. It then uses C# to parse individual characters from the message and concatenates them into image tags. Please examine the HTML in the sample by right-clicking on page and looking at the source code. You should see a textbox and one image tag for each character in the message.  Steps:
    1. The code for this exercise is in the class handout FontPickerCSharp.doc. Create a new model and controller using the names in the handout and paste in the code.
    2. To create a view right-click in either of the Index action handlers and select "New View."
    3. The controller uses the ViewBag to pass the string of image tags to the View. Add "@ViewBag.imageTags" to the View below the form. As a security feature the ViewBag does not render HTML tags so you need to wrap the ViewBag statement with @Html.Raw().
    4. Test.
  3. FontPicker/Fonts - This exercise extends FontPicker by adding a dropdown list of font names and displaying images for the selected font. Steps:
    1. Model: The ID of selected font needs to be stored. Add a new string property to FontPickerModel named FontId.
    2. ViewModel - The font names displayed in the dropdownlist are stored in the ViewModel, very similar to the previous exercise. In your ViewModel folder add a class named FontPickerViewModel. Copy the code from ListStatesViewModel and modify it to display fonts using the names below.
      FontName FontId
      Chunk Red ChunkRed
      Deco Blue DecoBlue
      Animals Animals
      Elegant Red ElegantRed
      Funky Funky
      Tape Punch TapePunch
    3. Controller: The controller from the previous exercise needs two additional ActionMethods to handle the new view "Fonts." Copy and paste the two existing controller named "Index" them and rename the copies "Fonts".
    4. View: Create a new view "Fonts" by right-clicking in one of the "Fonts" action methods and selecting "Add View..." View name is Fonts, template is "Create" and model class is FontPickerModel.  When viewed in a browser the view should contain two textboxes: Message and FontId.
    5. Replace the FontID textbox with a dropdown list. FontPickerController
    6. The model will pass the FontId of the selected font to the controller (see image showing debugger output).  Modify GenerateImageTags() to accept FontId as a second parameter of type string. The second parameter should be optional so that the method still works when a font ID is not specified. See How can you use optional parameters in C#?
    7. Within GenerateImageTags use an If else-if statement to select the appropriate image tags. To improve code readability I recommend creating a new method that contains this long if else if statement. It would look something like this: 
      private string GetTag(string character, string font)
                  string url = "<img src='";
                  if (font == "ChunkRed")
                      return url + "Chunk/red/" + character + "9.jpg' />";
                  else if (font == "DecoBlue")
                  *** truncated here ***
    8. The images for each font are stored in separate folders. Each font uses a slightly different naming convention. The naming convention for each font is (where x is the character desired) is shown in the table below. Look at the image tags in the sample to see a complete image path.
      Font Directory & File
      Chunk Red chunk/red/x9.jpg
      Deco Blue deco/blue/x1.gif
      Animals animals/x4.gif
      Elegant Red elegant/red/4x.gif
      Funky funky/x3.jpg
      Tape Punch punch/black/x7.gif
    9. Test your code. If any of the fonts do not display right-click on the web page and view source. Make sure that the path in your image tags match those in the sample.

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