In the previous article, I was writing about building basic CRUD scenarios using DotVVM, an open-source MVVM framework for the line of business web apps.
In this part, I would like to demonstrate how to make many CRUD screens using generic types in C# and how to build universal base classes with a few extensibility points. It is useful in larger applications with many CRUD screens as it significantly decreases the amount of code you need to write.
Again, I will be using the NorthwindStore DotVVM Demo project.
DotVVM uses C# classes as ViewModels. I would like to have two base classes for my ViewModels – one for the list page and one for the detail page.
The list page should allow the user to see data in the GridView control, with filtering, sorting, and paging. The records can also be deleted from the list page.
The details page should enable the user to insert or update a particular record.
Business Layer and Interfaces
The ViewModels must access the data somehow. In the demo project, I have a set of classes called Facades. They provide everything that I need to the viewmodels. How they work is out of the scope of this article; the important thing is that these Facades implement the following generic interface,
- public interface IListFacade<TDTO, TKey>
- {
- void FillDataSet(GridViewDataSet<TDTO> items);
- void Delete(TKey id);
- }
The FillDataSet method looks at the GridViewDataSet settings for paging and sorting and apply these settings to the SQL query.
The Delete method just deletes the record from the database, or mark it as deleted.
Notice that the façade has two types of arguments.
- TDTO (DTO stands for Data Transfer Object) is a type of object I want to show in the grid.
- TKey is a type of the primary key of the object. In most cases, it would be int, but there might be a situation where the key is different.
The façade for the detail page implements the following interface,
- public interface IDetailFacade<TDTO, TKey>
- {
- TDTO GetDetail(TKey id);
- TDTO InitializeNew();
- TDTO Save(TDTO item);
- }
The GetDetail method will find the record by its primary key and return the DTO with all data I need.
The InitializeNew method returns a new object with default values of properties. It is called whenever the user wants to insert a new record. Please note that this method does not store anything in the database – it only initializes a new DTO with default values.
The Save method takes care of both insert and update of the object. Since the database can fill some properties automatically (generate the primary key for example), the Save method returns the most current version of the DTO.
It does not matter how the facades are implemented. In my case, they are using Entity Framework and AutoMapper to work with the database and build DTO representations of entities.
As I wrote in the previous part – it is not a good idea to work with Entity Framework entities in the user interface and place them in the viewmodel – it could expose columns which the user should not see, as they are serialized in JSON, and it would cause a lot of other issues.
The DTOs also allow us to make a REST API and expose the same DTOs using the API, which may be useful when you need to build a mobile application.
Generic ViewModel for the list pages
Now I have facades which implement generic interfaces so that I can build generic viewmodels.
The base viewmodel for the list page can look like this,
- public abstract class ListPageViewModel<TDTO, TKey> : DotvvmViewModelBase
- where TDTO : new()
- {
- [Bind(Direction.None)]
- public IListFacade<TDTO, TKey> Facade { get; }
-
- public ListPageViewModel(IListFacade<TDTO, TKey> facade)
- {
- this.Facade = facade;
- }
-
-
- [Bind(Direction.None)]
- public abstract ISortingOptions DefaultSortOptions { get; }
-
- public GridViewDataSet<TDTO> Items { get; set; }
-
-
- public override Task Init()
- {
- Items = new BpGridViewDataSet<TDTO>()
- {
- PagingOptions =
- {
- PageSize = 50
- },
- SortingOptions = DefaultSortOptions
- };
-
- return base.Init();
- }
-
-
- public override Task PreRender()
- {
- if (!Context.IsPostBack || Items.IsRefreshRequired)
- {
- LoadData();
- }
-
- return base.PreRender();
- }
-
- private void LoadData()
- {
- OnDataLoading();
- Facade.FillDataSet(Items);
- OnDataLoaded();
- }
-
- public void Delete(TKey id)
- {
- OnItemDeleting(id);
- Facade.Delete(id);
- OnItemDeleted(id);
- }
-
- protected virtual void OnDataLoading()
- {
- }
-
- protected virtual void OnDataLoaded()
- {
- }
-
- protected virtual void OnItemDeleting(TKey id)
- {
- }
-
- protected virtual void OnItemDeleted(TKey id)
- {
- }
- }
First, look at the constructor of the viewmodel. It accepts IListFacade<TDTO, TKey> as a parameter. I will have all my facades registered in the service collection on application start so that the instance can be injected in the viewmodel automatically by DotVVM. Thanks to this, I do not need to use the façade constructor or call Dispose when the HTTP request ends.
After the constructor, I declare an abstract property which defines the default sort order of the records, and the GridViewDataSet itself. The GridViewDateSet is initialized in the Init phase.
In the PreRender phase, I am checking whether this is the first request to the page (IsPostBack is false) and whether the refresh is requested. The GridViewDataSet contains a flag that indicates that it should be refreshed, for example when the user changed the sort order.
Finally, the LoadData method calls FillDataSet on the façade. Similarly, the Delete method also calls the corresponding method on the façade. There are four extensibility points which can be overridden in derived classes to add extra functionality. In real-world applications, most CRUDs still have some extra functionality.
These extensibility points are empty virtual methods (so they could be overridden) that are called before and after the data is loaded, and before and after a record is deleted.
Using the generic list page
When I want to build a list page, I can now just inherit from the base class.
- public class ProductListViewModel : ListPageViewModel<ProductListDTO, int>
- {
-
- public ProductListViewModel(AdminProductsFacade facade) : base(facade)
- {
- }
-
- public override ISortingOptions DefaultSortOptions => new SortingOptions()
- {
- SortExpression = nameof(ProductListDTO.ProductName)
- };
- }
When you look at the generic parameters, you can see that I am using ProductListDTO as the DTO.
This class contains only the properties I need to display in the GridView control. The database table may contain some columns that aren’t necessary – SupplierID and CategoryID for example. Moreover, there are some columns in other tables which can be required, like the name of the supplier and category.
The ProductListDTO class is declared like this,
- public class ProductListDTO
- {
- public int Id { get; set; }
- public string ProductName { get; set; }
- public string SupplierName { get; set; }
- public string CategoryName { get; set; }
- public string QuantityPerUnit { get; set; }
- public decimal? UnitPrice { get; set; }
- public short? UnitsInStock { get; set; }
- public short? UnitsOnOrder { get; set; }
- public short? ReorderLevel { get; set; }
- public bool Discontinued { get; set; }
- }
It is very similar to the Product entity in the NorthwindStore.DAL project. But if you look closer, you will notice that SupplierID and CategoryID properties are missing. Instead, I have added SupplierName and CategoryName.
In the business layer, I am using AutoMapper to map these properties. You can look in the ProductMapping class to see how the mapping is done,
- mapper.CreateMap<Products, ProductListDTO>()
- .ForMember(p => p.SupplierName, m => m.MapFrom(p => p.Supplier.CompanyName))
- .ForMember(p => p.CategoryName, m => m.MapFrom(p => p.Category.CategoryName));
Notice that I have only specified these extra properties in the mapping configuration; the other ones are mapped automatically because they have the same names as in the Product entity.
The reason why I mention this is that I am using a different DTO for the detail page. In real-world applications, there may be much more fields in the detail page than in the list page. Having two different DTOs make the list page more efficient as I do not need to load data that I do not use. Thanks to AutoMapper, it is not a big deal to have multiple DTO classes for the same database table. I find it much more practical as I can change one DTO without breaking other places in the application which work with the same database table.
In the demo application, there are another two properties which are inherited from the viewmodel of the master page. They define the page title and the menu category which should be highlighted.
- public override string PageTitle => "Categories";
- public override string HighlightedMenuPath => "Categories";
Generic ViewModel for detail page
The viewmodel for detail page is implemented quite similarly. Again, it requests the facade in the constructor.
- public abstract class DetailPageViewModel<TDTO, TKey> : AdminViewModel
- where TDTO : IEntity<TKey>
- {
- [Bind(Direction.None)]
- public IDetailFacade<TDTO, TKey> Facade { get; }
-
- public DetailPageViewModel(IDetailFacade<TDTO, TKey> facade)
- {
- this.Facade = facade;
- }
-
-
- public abstract string ListPageRouteName { get; }
-
-
- public TKey CurrentItemId { get; set; }
-
- public bool IsNew => Equals(CurrentItemId, default(TKey));
-
- public TDTO CurrentItem { get; set; }
-
-
- public override Task Init()
- {
- if (Context.Parameters.ContainsKey("Id"))
- {
- CurrentItemId = (TKey) Convert.ChangeType(Context.Parameters["Id"], typeof(TKey));
- }
-
- return base.Init();
- }
-
- public override Task PreRender()
- {
- if (!Context.IsPostBack)
- {
- if (!IsNew)
- {
- CurrentItem = Facade.GetDetail(CurrentItemId);
- }
- else
- {
- CurrentItem = Facade.InitializeNew();
- }
- OnItemLoaded();
- }
-
- return base.PreRender();
- }
-
-
- protected virtual void OnItemLoaded()
- {
- }
-
- protected virtual void OnItemSaving()
- {
- }
-
- protected virtual void OnItemSaved()
- {
- }
-
-
- public void Save()
- {
- OnItemSaving();
-
- CurrentItem = Facade.Save(CurrentItem);
- CurrentItemId = CurrentItem.Id;
-
- OnItemSaved();
-
- Context.RedirectToRoute(ListPageRouteName);
- }
-
- public void Cancel()
- {
- Context.RedirectToRoute(ListPageRouteName);
- }
-
- }
The ListPageRouteName property specifies the name of the route of the list page. The viewmodel will redirect to it after the user saves the changes.
The CurrentItemId property is set in the Init phase with the value of the route parameter named “id”. If the parameter is not present, the page allows inserting a new record.
The CurrentItem property contains the DTO itself. No matter how complex the DTO is, how many nested objects or collections it contains, it is not difficult to build a user interface for that DTO with DotVVM and its two-way data-binding.
In the PreRender method, I am either initializing the new object for inserting or loading an existing object by the ID specified in the route. Both options simply call the appropriate methods in the façade. There is an extensibility point that can be used to perform an additional action after the DTO is initialized or loaded.
The Save method calls the corresponding method on the façade and again, it invokes an empty virtual method before and after the data is saved. Then, it redirects the user to the list page.
Using the generic detail page
The products page uses the base viewmodel to implement the base CRUD functionality,
- public class ProductDetailViewModel : DetailPageViewModel<ProductDetailDTO, int>
- {
- private readonly BaseListsFacade baseListsFacade;
-
- public ProductDetailViewModel(AdminProductsFacade facade) : base(facade)
- {
- this.baseListsFacade = baseListsFacade;
- }
-
- public override string ListPageRouteName => "Admin_ProductList";
-
- }
Notice that I am using ProductDetailDTO instead of ProductListDTO. As I have already pointed out, the DTO used in the detail page can be very different, and it can also manage related records – it can contain nested objects or collections.
My ProductDetailDTO does not contain SupplierName and CategoryName. Instead, there are the original SupplierID and CategoryID properties that can also be found in the Product entity. This is because I am using ComboBox controls in the user interface, and they work better with the ID properties.
The only thing they need in the viewmodel are the collections of suppliers and categories. I can add them in the viewmodel using the following code snippet,
- [Bind(Direction.ServerToClientFirstRequest)]
- public List<CategoryBasicDTO> Categories => baseListsFacade.GetCategories();
-
- [Bind(Direction.ServerToClientFirstRequest)]
- public List<SupplierBasicDTO> Suppliers => baseListsFacade.GetSuppliers();
Notice that these collections are decorated with the Bind attribute. This attribute tells DotVVM that these properties should only be transferred on the first request. There is no need to send them to the server on postback or back to the client as they cannot be changed. It helps DotVVM to optimize the amount of data transferred between the server and the client.
The ComboBox controls that select the supplier and category look like this,
- <div class="form-field">
- <label>Category</label>
- <div>
- <bp:DropDownList DataSource="{value: _root.Categories}"
- SelectedValue="{value: CategoryId}"
- ItemTextBinding="{value: CategoryName}"
- ItemValueBinding="{value: Id}" />
- </div>
- </div>
The DataSource property points to the list of all categories. Because the form uses DataContext property and thus, all bindings are evaluated on CurrentItem property, I need to use _root.Categories to tell DotVVM to look for the collection on the root viewmodel.
The SelectedValue property references the property which holds the value selected by the user.
The ItemTextBinding tells the control which property from the Categories collection should be displayed in the ComboBox, and the ItemValueBinding tells the control which property is used as the selected value.
Conclusion
I described the principles of making universal generic viewmodels for implementing CRUD screens in DotVVM. I have installed several extensibility points in the viewmodels so the pages may contain a custom logic.
Of course, these viewmodels should be adapted to match your application, so feel free to add more functionality or change anything if it makes sense.
In the next part of this article series, I’d like to show some more advanced customizations of this generic CRUD, that can be found in the NorthwindStore Demo app.
Resources