In MVC, use the concept of display/editor templates. They allow you to:
- Have more abstract views. Views then serve rather as more-specific layouts (in conjunction with your more-generic _Layout.cshtml).
- Store specific pages as objects of various CLR types in your persistent repository (be it EF or anything else)
The objects should be strongly typed and are supposed to be hierarchically composed of/aggregated of other objects representing the internal parts of the page.
Your views may then look like:
@model BikeStore.Models.BodyPartTwoSecondaryParts
<div class="container body-part">
@Html.DisplayFor(vm => vm.BodyPart)
</div>
<div class="container">
<div class="inline-block half-width secondary-part">
@Html.DisplayFor(vm => vm.FirstSecondaryPart)
</div>
<div class="inline-block half-width secondary-part">
@Html.DisplayFor(vm => vm.SecondSecondaryPart)
</div>
</div>
It is possible because MVC can automatically render a display/editor template once it sees that data of a certain CLR type appears in the view model. The template is basically an ordinary Razor file that has the same name as the CLR type.
The pages may even have several visual representations (templates) defined. It is possible to invoke them in various parts of the app (i.e. in various views) via custom HTML helpers:
For instance, a SearchResults.cshtml view might just call:
@foreach (var item in Model.SearchResults)
{
@Html.SearchResultFor(vm => item)
}
The HTML helper method would be:
public static MvcHtmlString SearchResultFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression)
{
string typeName = expression.ReturnType.Name;
return htmlHelper.DisplayFor(expression, $"{typeName}Search");
}
Another question is how to store pages of arbitrarily deep structures via Entity Framework. (I ommit the option to store their full HTML as nvarchar
data as this is what a CMS should help you to avoid.)
I cannot tell how complex such code would be. You might probably get inspired by a JSON de-serializing logic in our company's SDK. That method builds a strongly typed model that you can then pass into MVC views and rely on display templates.
If you wish to see the above code examples in context, take a look at one of my posts. You can also examine a working example app that's using our headless CMS as its persistent repository.