MVC Razor @foreach

后端 未结 5 1731
半阙折子戏
半阙折子戏 2020-11-27 13:13

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 sh

5条回答
  •  甜味超标
    2020-11-27 13:31

    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)
    {
        
    @item.Bar
    }

    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 Foos { get; set; }):

    @model Foo
    
    @Model.Bar

    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.

提交回复
热议问题