Skip to content

BeforeDisplay and BeforeSave

Jon P Smith edited this page Jan 15, 2019 · 1 revision

CrudServices cannot anticipate everything you need to do to display/edit data. One common issue is providing extra information, such as a information to create a dropdownlist, in a page. Also, sometimes you need to transform some data, like the input from a dropdownlist, to fill in a property needed for a create/update.

I therefore have developed a pattern consisting of two parts:

  • BeforeDisplay: This is a method in your DTO that you call before the page is displayed (or redisplayed when there is an error). Its job is to fill in any extra information needed for the page to work.
  • BeforeSave: This is a method in your DTO that you call just before the CrudServices' Create/Update method. Its job is to fill in any properties in the DTO needed for the create/update that aren't quite in the right form yet - say turning the returned value from a dropdownlist into a entity lookup.

To allow you to do this the CrudServices provides you with an instance of the DbContext that was injected into the CrudServices instance. This means you can write your own database code.

NOTE: you don't have to use my names or my style, but you will need something to handle the type of problem I describe. My pattern shows how you could do it.

Example of the BeforeDisplay/BeforeSave in action

The creation of a book needs a list of Author entities for the book. This isn't something that the razor page could return, so instead I added the following method to the CreateBookDto:

  1. A BeforeDisplay method that filled the AllPossibleAuthors a Key/Name list with the Key and name of every author.
  2. A BeforeSave method that filled Authors property with Author instances found from the keys in the multiselect list.

You can see the BeforeDisplay and BeforeSave methods in the CreateBookDto class.

See how these methods are used in the Home/Create.cshtmnl.cs PageModel uses these methods.

  • The BeforeDisplay has to be called in the OnGet handler, but also in the OnPost method when there are errors and the page needed to be redisplayed.
  • The BeforeSave method should be called just before the CreateAndSave method is called.