Razor Pages でのforループ - Razor Pages

Razor Pages でのforループの記述方法を紹介します。

概要

Razor Pagesではページ内にロジックのコードを記述できます。この記事では、Razor Pages内にfor ループを記述する方法を紹介します。

書式

コードブロック内で下記の書式を利用します。
for (初期値設定式; ループ条件式; ループ更新式){
...(処理)
}
C#と似た書式を利用します。

記述例

@{
  for (int i = 0; i < 16; i++) {
    <div>文字列</div>
  }
}

プログラム例

ASP.NET Core アプリケーションを作成し、Razor Pagesを作成します。

コード

Startup.cs を記述します。
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace RazorPagesControlFlow
{
  public class Startup
  {
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddRazorPages();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
      }

      app.UseRouting();

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapRazorPages();
      });
    }
  }
}

Pagesフォルダに下記のRazor Pagesを作成します。
SimpleForLoop.cshtml
@page  
<h3>Forループのデモ</h3>

<p>テスト</p>

@{
  for (int i = 0; i < 10; i++) {
    <p>テキスト: @i</p>
  }
}

<p>ページの終わり</p>

解説

下記がRazorページ内のforループになります。変数iの値を0に設定し、iが10より小さい場合にループを繰り返します。ループを一回実行するごとにiを1増やします。ループ内では <p>テキスト: @i</p> をページに出力しています。@i は変数iの値が入るため画面には、「テキスト: 0」「テキスト: 1」「テキスト: 2」「テキスト: 3」「テキスト: 4」「テキスト: 5」「テキスト: 6」「テキスト: 7」「テキスト: 8」「テキスト: 9」が表示されます。
@{
  for (int i = 0; i < 10; i++) {
    <p>テキスト: @i</p>
  }
}

実行結果

プロジェクトを実行し下記のURLを開きます。
https://(アプリケーションのURL)/SimpleForLoop

作成したSimpleForLoop.cshtml のRazorページが表示されます。forループが実行され、「テキスト:」の表示がループで指定した回数表示できていることが確認できます。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用

関連するページ

最終更新日: 2021-12-15
作成日: 2020-02-26
iPentec all rights reserverd.