Overriding the PageModel() constructer for setting up default properties (Razor Pages)

Viewed 156

I am new to Razor Pages and looking for the best way to solve my problem.

Say I have an IndexModel class, that has some properties that rely on a DB context that is injected via the Constructer, such as a drop down list of Membership Levels, that comes directly from a table...

My question is what is the best way to handle populating this drop down list that I have for ALL requests that results in the same page being reloaded / returned. I know that I can put logic in OnGet to set up the list, the problem arises if say in OnPost, ModelState.IsValid is false, and so the page is returned with Page(). If I don't explicitly reinitialize the select list in OnPost, then I get a null reference exception, which is fair enough. Rewriting the code in the OnPost method goes against DRY principles, so I looked to writing a ConfirgureProperties() method in the class when needed.

Then by testing, I found that I can just set up a constructer that will take care of populating properties for me whenever they are needed, and I don't have to call anything else. Even when DI is involved, the injection is resolved at the top of the constructer, then I can use the context to do what I need for the other properties later in the constructer. I have seen no examples of this anywhere online, I only ever see people using constructers in page models that handle DI EXCLUSIVELY.

Is there a reason I SHOULD NOT be doing this, like bad coding practice or something, or is it ok for me to use page model constructers in this way?

Thanks

1 Answers

You only need to make the database call to repopulate the options in OnPost if ModelState is invalid. Chances are, if you have set up your validation correctly, that 99% of the time validation errors will be caught on the client and you won't need to repopulate the options.

Obtaining data from a database is costly, and you should only do it when necessary. So using the constructor approach contravenes this principal.

It's not like you are saving a lot of code either. Your ConfigureProperties method will only be called in two places in the PageModel.

Related