Date Published: January 26, 2021
I really like using Razor Pages with Microsoft MVC, as these work very well for simple web applications. One of the more useful features of Razor Pages are partials, which can really help reduce duplication between pages.
I'm currently working on a project to add a checkout interface to a web app, but due to some quirks of the payment provider we are using, there need to be two checkout pages: one for a monthly subscription, and one for an annual subscription. Since the only real difference between these two is the name and price of the plan at the top of the page and the information being passed to the payment provider, the pages are nearly identical. Obviously, this violates the DRY Principle.
This is where partials come in. Partials are Razor Views (a Razor View consists of just a .cshtml page, as opposed to a Razor Page, which has both the .cshtml page and the .cshtml.cs backend). These partials can be used to virtually eliminate duplication, as they support parameters being passed in via a ViewModel/DTO (data transfer object). My checkout page problem was very well-suited to a partial, since I was able to create a simple DTO with the few differences between the two pages.
The process for cleaning up duplication between pages using a partial is pretty simple.
Create your DTO. For example, SubscriptionTypeViewModel
Name
, Price
, SubscriptionPeriod
Create a new Razor View and name it _NameOfPage
_NameOfPagePartial
for additional clarity@model Full.Path.Of.SubscriptionTypeViewModel
From this point, I found it easiest to copy-paste the contents of one of my duplicate pages (for me, this was essentially the whole page, but for you it may only be a small portion of that page, which is duplicated elsewhere) into my Partial. From here, it was easy enough to replace any information specific to either page with a call to the model.
<h1>Purchase Monthly Plan</h1>
becomes <h1>Purchase @Model.Name Plan</h1>
At this point, you are almost done! Congrats! All that's left are a few simple plumbing bits. First, add a property of the same type as your DTO (e.g. SubscriptionTypeViewModel
) to the model for each of your duplicate pages (the .cshtml.cs file)
SubscriptionType.Name = "Monthly"
, etc.)<partial name="_NameOfPage" for="SubscriptionType" />
, where "SubscriptionType" was the name of the DTO property of type SubscriptionTypeViewModel
for that page.As this is a refactoring, your pages should now look exactly as they did before you began this process. But you have vastly increased their maintainability.
For more information on partials, here are some useful docs:
Thanks for reading! I hope you find this and other articles here at ilyanaDev helpful! Be sure to follow me on Twitter @ilyanaDev.