ASP.NET core MVC 検索機能を作成する

ASP.NET core MVC 検索機能を作成する

ASP.NET core MVCで、検索機能を作成する手順を記述してます。.NETのバージョンは6を使用してます。

環境

  • OS windows10 pro
  • IDE Visual Studio 2022
  • .NET 6

プロジェクト作成

「ASP.NET Core Web アプリ(Model-View-Controller)」を選択してプロジェクトを作成してます。

SQLServer

「hoge」というDBにある「member」テーブルを使用します。

「member」テーブルに、以下のデータを作成してます。

EntityFrameworkCore追加

使用するパッケージを追加しておきます。

「ツール」 > 「NuGet パッケージ マネージャー」 > 「パッケージ マネージャー コンソール」を選択します。

以下の2つを作成したプロジェクトに追加しておきます。

PM> Install-Package -ProjectName プロジェクト名 -Id Microsoft.EntityFrameworkCore.SqlServer
PM> Install-Package -ProjectName プロジェクト名 -Id Microsoft.EntityFrameworkCore.Tools

Model作成

DBに接続して作成します。Scaffold-DbContextを使用して、以下のコマンドを実行してModelを作成します。

DB名 : hoge
ホスト : 192.168.xxx.xxx
ユーザー : sa
パスワード : password
modelを作成するフォルダ : Models
コンテキスト名 : MemberDbContext

PM> Scaffold-DbContext -Provider Microsoft.EntityFrameworkCore.SqlServer -Connection "Data Source=192.168.xxx.xxx;Database=hoge;user id=sa;password=password" -f -OutputDir "Models" -Context "MemberDbContext" -UseDatabaseNames -DataAnnotations

「Models」フォルダ配下に「Model」と「Context」が作成されていることが確認できます。

「MemberDbContext.cs」に記述されているDB接続情報は使用しないので、コメントアウトしておきます。

//        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
//        {
//            if (!optionsBuilder.IsConfigured)
//            {
//#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
//                optionsBuilder.UseSqlServer("Data Source=192.168.xxx.xxx;Database=hoge;user id=sa;password=password");
//            }
//        }

DB接続情報

sqlserverと接続できるように接続情報を追加します。

「appsettings.json」に、以下のコードを追加します。

「ConnectionStrings」を追加します。

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=192.168.xxx.xxx;Database=hoge;User ID=sa;Password=password;"
  }
}

サービス登録

サービスに、コンテキストを登録します。「Program.cs」を編集します。

さきほど「appsettings.json」に作成した接続情報「DefaultConnection」を使用して「MemberDbContext」を登録します。

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

// 追加
builder.Services.AddDbContext<MemberDbContext>(
    options => options.UseSqlServer(
        builder.Configuration.GetConnectionString("DefaultConnection")
        )
    );

スキャフォールド

ここではスキャフォールドを使用して、ViewとControllersを作成してCRUDを作成します。

「Controllers」フォルダを右クリックして「新規スキャフォールディングアイテム」をクリックします。

「Entity Frameworkを使用したビューがあるMVCコントローラー」を選択して、「追加」をクリックします。

さきほど、作成したモデルとデータコンテキストを選択して、「追加」をクリックします。

実行

一度、「F5」キーでデバックを実行して、起動します。

http://localhost:ポート番号/members/ にアクセスするとCRUDが作成されていることが確認できます。

検索機能追加

「Controllers」フォルダ配下に作成された「membersController.cs」を編集します。

Indexメソッドを以下のコードに編集して、検索ワードあるなしにより結果を変更します。

        // GET: members
        public async Task<IActionResult> Index(string strSearch)
        {
            // LINQを使用して全データを取得
            var members = from m in _context.members
                          select m;

            // 検索ワードがあればlikeで結果を取得します
            if (!String.IsNullOrEmpty(strSearch))
            {
                members = members.Where(s => s.month.Contains(strSearch));
            }
            return View(await members.ToListAsync());
        }

次に「Views > members」フォルダ配下にある「Index.cshtml」にも検索窓を追加しておきます。

formを追加します。

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<form asp-controller="members" asp-action="Index" method="get">
    <div class="row">
        <div class="col">
            <input class="form-control" type="text" name="strSearch" />    
        </div>
        <div class="col">
            <input class="btn btn-primary" type="submit" value="検索" />
        </div>
    </div>
</form>

「F5」キーでデバックを実行して、起動して「http://localhost:ポート番号/members/」にアクセスします。

指定した検索ワードで、検索した結果が表示されていることが確認できます。