Today I do something like this, where I get, select and sort some data and pass it on to the view (which loads a partial view) as a list of custom objects
Page model
public PagesSettings PageSettings { get; set; }
public List<Reportage> itemListReportages { get; set; }
public void OnGet()
{
PageSettings = (PagesSettings)HttpContext.Items["pagesettings"];
if (PageSettings == null)
{
return;
}
var fileContent = _fileService.GetFileContentCached(PageSettings.DataFile);
if (fileContent?.Length > 0)
{
itemListReportages = (JsonConvert.DeserializeObject<List<Reportage>>(fileContent))
.Where(l => l.Published)
.OrderBy(l => l.Name)
.ToList();
}
}
Page view
@page
@model ListReportagesModel
@if (Model.PageSettings?.Data?.Count > 1 && Model.PageSettings.Data[1].Html?.Length > 0)
{
<section class="content @(Model.PageSettings.SectionClass ?? "")">
<div>
@if (Model.PageSettings.Data[1].Values?.Length > 0)
{
@Html.Raw(String.Format(Model.PageSettings.Data[1].Html, Model.PageSettings.Data[1].Values))
}
else
{
@Html.Raw(@Model.PageSettings.Data[1].Html)
}
</div>
</section>
}
<section class="content @(Model.PageSettings.SectionClass ?? "")">
<div class="aflex aflexwrap aflexspacebetween">
<partial name="/Pages/Partial/@Model.PageSettings.PartialView" />
</div>
</section>
Partial view
@for (var i = 0; i < Model.itemListReportages.Count; i++)
{
<div class="item">
<div class="itembkg" style="background-image: url('@Model.itemListReportages[i].BkgImage');"></div>
<div class="itemtxt">
<span>@Model.itemListReportages[i].Text</span>
</div>
</div>
}
It now start to become a lot of PageModel
's, so I started to wonder where the proper location to run C# code is. In above the data loading/select/sort is done in the PageModel
and the rest in the view's.
I was planning to split it up like below instead, moving the select/sort from Pagemodel
to the partial view, and with that reduce the amount of Pagemodel
's and make it simpler to add data by simply create a new class + data file + partial view.
The question, which way is recommended (if any), perform select/sort in PageModel
or in View
?
Page model
public PagesSettings PageSettings { get; set; }
public string fileContent { get; set; }
public void OnGet()
{
PageSettings = (PagesSettings)HttpContext.Items["pagesettings"];
if (PageSettings == null)
{
return;
}
fileContent = _fileService.GetFileContentCached(PageSettings.DataFile);
}
Partial view
if (fileContent?.Length > 0)
{
var itemListReportages = (JsonConvert.DeserializeObject<List<Reportage>>(fileContent))
.Where(l => l.Published)
.OrderBy(l => l.Name)
.ToList();
@for (var i = 0; i < Model.itemListReportages.Count; i++)
{
<div class="item">
<div class="itembkg" style="background-image: url('@Model.itemListReportages[i].BkgImage');"></div>
<div class="itemtxt">
<span>@Model.itemListReportages[i].Text</span>
</div>
</div>
}
}