I heard that having @foreach inside of a view is a no-no. Meaning, the view should not have any logic in it. What is the best practice on where the logic for the @foreach should be at?
@foreach..
You can add support for Pages to any ASP.NET Core MVC app by simply adding a Pages folder and adding Razor Pages files to this folder. Razor Pages use the folder structure as a convention for routing requests.
From the docs, "Razor Pages can make coding page-focused scenarios easier and more productive than using controllers and views." If your ASP.NET MVC app makes heavy use of views, you may want to consider migrating from actions and views to Razor Pages.
A Razor Page is almost the same as ASP.NET MVC's view component. It has basically the syntax and functionality same as MVC. The basic difference between Razor pages and MVC is that the model and controller code is also added within the Razor Page itself. You do not need to add code separately.
The view model pattern is used extensively in MVC application development, where it mainly represents data, but typically little behaviour. In Razor Pages, the PageModel is also the view model. Razor Pages is sometimes described as implementing the MVVM (Model, View ViewModel) pattern.
What is the best practice on where the logic for the @foreach should be at?
Nowhere, just get rid of it. You could use editor or display templates.
So for example:
@foreach (var item in Model.Foos) { <div>@item.Bar</div> }
could perfectly fine be replaced by a display template:
@Html.DisplayFor(x => x.Foos)
and then you will define the corresponding display template (if you don't like the default one). So you would define a reusable template ~/Views/Shared/DisplayTemplates/Foo.cshtml
which will automatically be rendered by the framework for each element of the Foos collection (IEnumerable<Foo> Foos { get; set; }
):
@model Foo <div>@Model.Bar</div>
Obviously exactly the same conventions apply for editor templates which should be used in case you want to show some input fields allowing you to edit the view model in contrast to just displaying it as readonly.
When people say don't put logic in views, they're usually referring to business logic, not rendering logic. In my humble opinion, I think using @foreach in views is perfectly fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With