Visual Studio MVCモデル開発でjQueryのDatepickerを実装する方法

プログラミング

(この記事は2022年7月5日が最終更新日です。)

自己紹介

この記事の作成はKazuが行っています。
本業ではエンジニアとして働きつつWebサービス開発を行っております。
副業でWebエンジニア・デザインを行っています。

エンジニアに欠かせないのが学習という名の自己投資です。

いろいろな学習方法があって正直どれを選べばよいのか悩みますよね・・・

いくつもある学習方法の中から私がオススメするのはUdemy!!

購入したコースが満足いく内容でなければ返金もしてくれるので損はありません。

Udemyを試してみる!

本記事ではVisual StudioでjQueryのDatepicker・Datetimepickerを実装する方法をご紹介してきます。

業務の中で勉強した内容の備忘録として。ご活用ください。

.Net CoreではデフォルトでDatepickerが実装されているのに、.Net Frameworkでは実装されていません。そこで今回は.Net Frameworkでも実装したと思った次第です。

完成した機能はこんな感じ。

【開発環境】 Visual Studio 2017 フレームワーク:.Net Framework 4.6 MVCモデル開発

.NetFrameworkを使用ていれば今回の内容でしたら他のバージョンでも動くと思います。.Net Coreでもいけると思います。

前提条件

Visual Studioの機能、スキャフォールディングを用いて基本的なデータ追加/更新/削除はできることとして、今回は追加のページにDatepicker・Datetimepickerを用いてカレンダーを実装していこうと思います。

jQueryのDatepickerの基本的な内容が知りたい方は以下の記事でHTMLで実装してるのでそちらをご覧ください。

Visual StudioにDatepickerを実装する

Visual StudioでMVCモデルで開発する際、Viewは基本的にはhtmlと変わりありません。

修正する点は以下の通り。

まずはレイアウトページのhead部分にcssを追加します。

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-datetimepicker@2.5.20/jquery.datetimepicker.css">
</head>
<body>
    <div class="container">
        @if (Request.IsAuthenticated)
        {
            @Html.ActionLink("ログアウト", "SignOut", new { Controller = "Login" })

            if (User.IsInRole("Administrators"))
            {
                <span> | </span>
                @Html.ActionLink("ユーザー管理", "Index", new { Controller = "Users" })
            }
        }
    </div>
    <div class="container">
        @RenderBody()
    </div>
</body>
</html>

次にCreate.cshtmlを修正します。

@model TodoApp2017.Models.Todo

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/_LayoutPage1.cshtml";
}

<h2>Create</h2>

@if (ViewData != null)
{
    <p>@ViewData["Message"]</p>
}


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Todo</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Summary, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Summary, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Summary, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Detail, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Detail, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Detail, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Limit, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Limit, new { htmlAttributes = new { @class = "form-control input1" } })
                @Html.ValidationMessageFor(model => model.Limit, "", new { @class = "text-danger" })
            </div>
        </div>
        @*
            <div class="form-group">
                @Html.LabelFor(model => model.Done, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    <div class="checkbox">
                        @Html.EditorFor(model => model.Done)
                        @Html.ValidationMessageFor(model => model.Done, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
        *@
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/i18n/jquery.ui.datepicker-ja.min.js"></script>
<script>
    $(function () {
        $.datepicker.setDefaults($.datepicker.regional["ja"]);
        $(".input1").datepicker();
    });
</script>

解説

今回、理解する点は2つ。

  • CSSの追加
  • jQueryの読み込みとdatepickerメソッドの呼び出し
  • 要素へのクラス名追加

CSSの追加

_LayoutPage1.cshtmlに追加したのは2行だけです。後ほど使うdatetimepickerのcssも一緒に追加しています。

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-datetimepicker@2.5.20/jquery.datetimepicker.css">

jQueryの読み込みとdatepickerメソッドの呼び出し

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/i18n/jquery.ui.datepicker-ja.min.js"></script>
<script>
    $(function () {
        $.datepicker.setDefaults($.datepicker.regional["ja"]);
        $(".input1").datepicker();
    });
</script>

上3行はjQueryの読み込みです。

その下のfunctionのところがdatepickerを呼び出しています。

要素へのクラス名追加

<div class="form-group">
    @Html.LabelFor(model => model.Limit, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Limit, new { htmlAttributes = new { @class = "form-control input1" } })
        @Html.ValidationMessageFor(model => model.Limit, "", new { @class = "text-danger" })
    </div>
</div>

@Html.EditorForのクラス名を追加する記述に今回使用する[ input1 ]を追加しています。

デバックするとこんな感じ。

期限の項目に入力しようとするとカレンダーが表示されます。

カレンダー上で日杖を選択するとちゃんと日付が入力されることが確認できます。

Visual StudioにDatetimepickerを実装する

処理自体はdatepickerと同じで、呼び出してあげるメソッドをdatetimepickerに変更するだけです。

@model TodoApp2017.Models.Todo

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/_LayoutPage1.cshtml";
}

<h2>Create</h2>

@if (ViewData != null)
{
    <p>@ViewData["Message"]</p>
}


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Todo</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Summary, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Summary, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Summary, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Detail, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Detail, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Detail, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Limit, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Limit, new { htmlAttributes = new { @class = "form-control input1" } })
                @Html.ValidationMessageFor(model => model.Limit, "", new { @class = "text-danger" })
            </div>
        </div>
        @*
            <div class="form-group">
                @Html.LabelFor(model => model.Done, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    <div class="checkbox">
                        @Html.EditorFor(model => model.Done)
                        @Html.ValidationMessageFor(model => model.Done, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
        *@
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-datetimepicker@2.5.20/build/jquery.datetimepicker.full.min.js"></script>
<script type="text/javascript">
    $(function () {
        $(".input1").datetimepicker();
    });
</script>

デバックするとこんな感じ。

日付だけでなく、時刻も入力できるようになっています。

最後に

繰り返しになりますが、システムエンジニアとして生きていく上で勉強は欠かせません!
書籍を購入して勉強するのもいいですが専門書は高いし、質問もできません。
私はいつも世界最大級のオンライン学習サイトUdemyで学習を行っています。
Udemyでは具体的な方法を教えてくれるし質問も可能なのでとても学習しやすいと感じています。
セールも定期的に実施されています。90%オフの講義もたくさんあるのでセールのタイミングを狙って購入しています。

「Udemy」公式サイト

コメント

タイトルとURLをコピーしました