NET 6 - Model

Last modified: March 25, 2022

MVVM (Model-View-ViewModel) is a separation pattern which extend version of MVC. Both aim for separation of concern so that parts of the application are not tightly coupled. View Model even makes it more separate between logic and presentation layer. The key advantage is a true separation between the View and Model.

When we need to format the model, View Model comes into the picture. For example, let say when we have a date property in the Model, and we want to format it to a specific format, then View Model helps.

View Model also comes in handy when we need to join more than one model and return a single object to the view.

Testing the UI is also hard, but the separation patterns with MVVM make it easier and quicker to perform testing.

1. Add View Models

  • Select TicketingSystem.Service project

EventViewModel

Create an ViewModel folder in the each UI project and the create EventViewModel class file in it. To make a field mandatory, we use the required [Required] annotation. for making a field maximum length we used [StringLength(500)]

public class EventViewModel { public string Id { get; set; } [Required] [StringLength(100)] public string Name { get; set; } [Required] [StringLength(500)] public string Location { get; set; } [Required] public DateTime Date { get; set; } }

EventBookingViewModel

We also need to create EventBookingViewModel.

public class EventBookingViewModel { public string Id { get; set; } public string Email { get; set; } public string EventName { get; set; } [Required] public string EventId { get; set; } public IEnumerable<EventViewModel> Events { get; set; } // use for dropdown list }