Exercises

Let’s practice adding more properties to our event objects and validating them. Create a new branch from the viewmodels .

Below, we describe some new properties for you to add to the Event class. For each property, consider the following factors:

  1. What will you call your property?
  2. What type of input should be added to capture the field’s information from the user?
  3. Refer to the chapter content to find appropriate attributes to fit the necessary constraints.
  4. What should the error message convey to the user?
  5. What, if anything, will you need to update on the controller to account for the new property?

Event information to add:

  1. Add a property to collect information about where the event will take place. This property should not be null or blank.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    
    // In the Event class
    
    public string Location { get; set; }
    
       //  In the Event constructor
       public Event( ... string location)
          {
    
                Location = location;
    
          }

    This property should not be null or blank.

    1
    2
    3
    4
    
    // In the AddEventViewModel class
    
    [Required(ErrorMessage = "Location information is required.")]
    public string Location { get; set; }
  2. Add a property to collect information about the number of attendees for the event. Valid values for this property should be any number between zero and 100,000.

  3. Add columns for the location and number of attendees to the Events/Index.cshtml view.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    <!-- inside your table -->
       <th>
          Location
       </th>
       <th>
          Number of Attendees
       </th>
       @foreach (var evt in Model)
       {
          <tr>
                <td>@evt.Id</td>
                <td>@evt.Name</td>
                <td>@evt.Description</td>
                <td>@evt.ContactEmail</td>
                <td>@evt.Location</td>
                <td>@evt.NumberOfAttendees</td>
          </tr>
       }
    </table>

Bonus Mission

Add a property to collect information about whether an attendee must register for the event or not. For the purposes of validation practice, make this property only able to be marked as true.

Tip

In order to do this, you need to add an additional property called IsTrue to AddEventViewModel with the following code:

1
public bool IsTrue { get { return true; } }

With IsTrue in AddEventViewModel, you can use a [Compare] attribute to compare the value of the IsTrue property which is always true and the value of the property you add for registration requirements. The documentation has more information on how the [Compare] attribute.