Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Razor @foreach

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..  
like image 782
Nate Pet Avatar asked Jun 29 '12 12:06

Nate Pet


People also ask

Can you use MVC with Razor pages?

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.

Which is better MVC or Razor?

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.

What is difference between MVC and 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.

Is Razor pages MVC or MVVM?

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.


2 Answers

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.

like image 71
Darin Dimitrov Avatar answered Sep 20 '22 17:09

Darin Dimitrov


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.

like image 44
JonoW Avatar answered Sep 17 '22 17:09

JonoW