#概要
ASP.NET Core MVC を使用したWEBアプリケーションにて
Ajaxを使用して動的にデータを表示するモダールウィンドウを実装してみました。
実装例として、
クリックしたボタンに埋め込まれているIDを持つユーザー名をモダール上に表示します。
#開発環境
ASP.NET Core 3.1
BootStrap
jquery
#ステップ
①モダールウィンドウ用のViewを追加
②モダールウィンドウを呼び出すViewを追加
③Contorollerを追加
④Ajaxの処理を追加
#詳細
##①モダールウィンドウ用のViewを追加
Views/Sharedにモダールウィンドウ用のView _Modal.cshtml を作成
<!-- 表示データ用のモデルを定義 -->
@model User
<!-- モダールの中身 -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<dt class = "col-sm-2">
ユーザー名:
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.Username)
</dd>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
※上記のコードは BootStrapのドキュメントよりそのまま引用してます
##②モダールウィンドウを呼び出すViewを追加
//①モダールウィンドウを表示させたい既存のViewに呼び出し用のボタンを追加します
<button type="button" class="btn btn-primary" id="#botton_for_openmodal" data-id="@item.Id" data-url="@Url.Action("ShowModal")">
Click Here
</button>
//モダール表示用のスペースを追加
<div id="ModalHere">
</div>
・呼び出したいコントローラー名へのパスをdata-xxxの形で記述
→渡したいデータがある場合は、data-xxx = "hogehoge"のような形で指定できます
##③Contorollerを追加
public class HogeController : Controller
{
private readonly ApplicationDbContext _context;
public HogeController(ApplicationDbContext context)
{
_context = context;
}
public async Task<ActionResult> ShowModal(string? id)
{
//何かしらの処理を記述
//今回はボタンから取得したIDに紐づくのユーザー情報を取得
var user =await _context.Users.FirstOrDefaultAsync(m => m.Id == id);
//呼び出したいモダール用のViewを指定(①で作ったもの)
//渡したいデータは第二引数とする
return PartialView("_EditModal", user);
}
}
##④Ajaxの処理を追加
基本的に通常のajax実装方法と変わりません!
$(document).ready(function () {
$('#botton_for_openmodal').click(function () {
var url = $(this).data('url');
var id = $(this).attr('data-id');
$.ajax({
url: url + '/' + id,
type: 'get',
cache: false,
})
.done(function (response) {
$("#ModalHere").html(response);
$("#ModalHere").find('.modal').modal('show');
})
.fail(function (xhr) {
console.log(xhr);
})
.always(function (xhr, msg) {
console.log(xhr,msg);
});
});
});
#完成
完成はこんな感じになります!!!
表示されるユーザー名がDBからの取得結果に応じて変化します。
#感想
簡単な実装サンプルにはなりましたが、
Scaffoldingで作成されるCRUD用のViewはページ遷移を基本としているので、
画面遷移なしでフォーム部分をモダールでサクッと実装したいなどの要件があるのではないかと思い書いてみました!
ASP.NET Core MVCのアプリを作成しようとすると、
BootSrtapとJqueryが最初から読み込まれているので、今回はそれを活用したサンプルになっています。
初めての投稿なので、分かりにくい箇所等あったかもしれませんが、
最後まで読んでいただきありがとうございました!!!