Best practice for re-using single view file for multiple pages with slightly different content

softwareengineering.stackexchange https://softwareengineering.stackexchange.com/questions/392825

  •  26-02-2021
  •  | 
  •  

Pregunta

If you have a view file which you want to re-use for different pages which have, for example, slightly different page headings, is there a 'best approach' of the three below? (Considering separation of concerns, business/presentation logic, etc.)

As an example, if I have the same ‘What is your address’ page but for a number of different account types e.g. charity account, personal account, business account, etc. which need different page headings respectively.

(a) Pass in the specific page heading in the controllers

  • CharityAccountController: return h.view({ pageHeading: "What is the charity's registered address?"})
  • PersonalAccountController: return h.view({ pageHeading: "What is your address?"})
  • View file: <pageHeading>{{ pageHeading }}</pageHeading>

(b) Pass in an account type flag in the controller and have some conditional logic in the view to set the heading:

  • CharityAccountController: return h.view({ isCharityAccount: true })
  • PersonalAccountController: return h.view({ isPersonalAccount: true })
  • View file: <pageHeading> { if isCharityAccount } What is the charity's registered address? { else if isPersonalAccount } What is your address? { else … } </pageHeading>

(c) Use separate view files for each page, abstracting as much as possible to common 'partials'

There may also be other page elements specific to account types e.g. hint text, validation error messages. And certain elements may need to be shown/hidden depending on the account type.

¿Fue útil?

Solución

You really have two things: a page and a reusable address component.

Each page should have its own view model, but each view model could hold a reference to an instance of a class that represents the address fields. That way you can create a shared template for the address fields used on all three pages, yet keep each page separate to reflect the fact they are different use cases.

Really it all comes back to favoring composition over inheritance. Composition is a great way to reuse code and keep loose coupling.

Otros consejos

In my opinion, you should go with option C. What you can do is you can create a partial view of common things. For different pieces of stuff, you can use the if conditions using Razor syntax. Like

`@{if(Viewbag.Title == "PersonalAccount")
   { 
      // your code 
   }
  }.` 

You can store the value in the ViewBag when you call the index method of a particular controller for the first time.

Licenciado bajo: CC-BY-SA con atribución
scroll top