質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

ASP.NET MVC Framework

ASP.NET MVC Frameworkは、MVCパターンをベースとした、マイクロソフトのウェブアプリケーション開発用のフレームワークです。

Q&A

解決済

2回答

5458閲覧

ASP.NET MVC5でボタンクリックでテキストボックスに定型文を挿入する

blackdifferent

総合スコア25

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

ASP.NET MVC Framework

ASP.NET MVC Frameworkは、MVCパターンをベースとした、マイクロソフトのウェブアプリケーション開発用のフレームワークです。

0グッド

0クリップ

投稿2018/12/06 07:38

編集2019/01/08 01:48

こんにちわ。
現在ASP.NET MVC5(VisualStudio2017)で下図のようなWeb勤務表を作っています。
「定時」ボタンを押したときにある決められた時刻を始業時刻と終業時刻に挿入したいのですが、なかなかできなくて困ってます。たとえば定時ボタンを押すと開始時刻に9:00、終業時刻に18:00とテキストボックスに入るようにしたいです。
下記に画面のスクショとコードを載せておきます。よろしくお願いします。
イメージ説明
ビュー:

@model IList<Kintai_CS_.Models.TKintai> @{ /**/ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; Dictionary<int, SelectList> dictionary = (Dictionary<int, SelectList>)ViewBag.Situation; } <h2>11月</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <table class="table"> <tr> <th> <nobr>日付</nobr> </th> <th> <nobr>曜日</nobr> </th> <th> <nobr>始業時刻</nobr> </th> <th> <nobr>終業時刻</nobr> </th> <th> <nobr>休憩時間</nobr> </th> <th> <nobr>所定時間</nobr> </th> <th> <nobr>残業時間</nobr> </th> <th> <nobr>勤怠状況</nobr> </th> <th> <nobr>補助</nobr> </th> <th> <nobr>備考</nobr> </th> </tr> @for (int i = 0; i < Model.Count; i++) { int idx = i; <tr> <td> @Html.DisplayFor(model => model[idx].id) @Html.HiddenFor(model => model[idx].id) </td> <td> @Html.DisplayFor(model => model[idx].week) @Html.HiddenFor(model => model[idx].week) </td> <td> @Html.EditorFor(model => model[idx].open, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model[idx].open, "", new { @class = "text-danger" }) </td> <td> @Html.EditorFor(model => model[idx].close, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model[idx].close, "", new { @class = "text-danger" }) </td> <td> @Html.EditorFor(model => model[idx].rest, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model[idx].rest, "", new { @class = "text-danger" }) </td> <td> @Html.DisplayFor(model => model[idx].worktime) @Html.HiddenFor(model => model[idx].worktime) </td> <td> @Html.DisplayFor(model => model[idx].overtime) @Html.HiddenFor(model => model[idx].overtime) </td> <td> @Html.DropDownListFor(model => model[idx].situation, dictionary[Model[idx].situation], new { htmlAttributes = new { @class = "form-control" } }) </td> <td style="width: 66px"> <nobr> <button type="button" onclick="location.href='@Url.Action("BtnClick","Kintai")'">定時</button> </nobr> </td> <td> @Html.EditorFor(model => model[idx].remark, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model[idx].remark, "", new { @class = "text-danger" }) </td> </tr> } </table> <p> <input type="submit" value="更新" /> </p> }

コントローラ:

using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using Kintai_CS_.Models; namespace Kintai_CS_.Controllers { public class TKintaisController : Controller { private mvcdbEntities db = new mvcdbEntities(); // GET: TKintais public ActionResult Index() { //選択ボックスのオプションを準備 List<TSituation> situations = db.TSituation.ToList(); Dictionary<int, SelectList> dictionary = new Dictionary<int, SelectList>(); foreach (TSituation item in situations) { dictionary.Add(item.id, new SelectList(situations, "ID", "Situation", item.id)); } ViewBag.Situation = dictionary; return View(db.TKintai.ToList()); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Index(List<TKintai> products) { foreach(var kintai in products) { TKintai sv_product = db.TKintai.Find(kintai.id); sv_product.open = kintai.open; sv_product.close = kintai.close; sv_product.rest = kintai.rest; sv_product.situation = kintai.situation; sv_product.remark = kintai.remark; if (kintai.open != null && kintai.close != null && kintai.rest != null) { kintai.worktime = kintai.close - kintai.open - kintai.rest; kintai.overtime = kintai.worktime - TimeSpan.FromHours(8); } } db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

ベストアンサー

定時ボタンを押すと開始時刻に9:00、終業時刻に18:00とテキストボックスに入るようにしたいです。

そういうのは JavaScript / jQuery で実現するのがよさそうです。

ところで、質問のコードの中の、

onclick="location.href='@Url.Action("BtnClick","Kintai")'"

は何なのでしょうか? それでやりたいことができるのでしょうか? できるのならその方向で進めてください。

できないのなら・・・

自分が思いつくのは、例えば setTime(tb1, tb2) というような JavaScript のメソッドを定義。「始業時刻」テキストボックスの id を tb1 に、「終業時刻」テキストボックスの id を tb2 に設定。それを button の onclick 属性に設定。ボタンクリックで setTime(tb1, tb2) を起動。引数 tb1, tb2 に与えられた id から対象のテキストボックスを取得。テキストボックスの value 属性に、それぞれ 9:00、18:00 を設定・・・というものです。

問題は id の取得ですが、MVC4 以降には Html ヘルパーに IdFor メソッドが用意されていて、それを使えば可能だと思います。

【追伸】

迷走しそうな雰囲気なので、そうならないようサンプルを書いておきます。

Html ヘルパー IdFor を使ってテキストボックス <input type="text" id="xxxxx" ... /> の id 属性の値 xxxxx を取得し、当該テキスト value 属性の値を書き換えるサンプルを書いておきます。

View のコードにだけ以下のように手を加えれば OK です。

以下の @model... と IdFor メソッドの引数は、前のスレッドの私のサンプルの Model ベースです。そこは質門者さんのケースに合わせて書き換える必要があります。(IdFor の引数は当該テキストボックスの EditorFor の第 1 引数と同じで良いと思います)

@model Mvc5App.Models.KintaiModel ・・・中略・・・ <button type="button" onclick="setRegularWorkTime('@Html.IdFor(model => model.Kintais[i].Open)', '@Html.IdFor(model => model.Kintais[i].Close)')" class="btn btn-primary"> 定時 </button> ・・・中略・・・ @section Scripts { @Scripts.Render("~/bundles/jqueryval") <script type="text/javascript"> //<![CDATA[ function setRegularWorkTime(from, to) { document.getElementById(from).value = "9:00"; document.getElementById(to).value = "18:00"; } //]]> </script> }

上の JavaScript のコードにより、以下の画像の赤枠で囲った部分が示すように、[定時]ボタンクリックで open, close テキストボックスの値が 9:00, 18:00 に書き換えられています。

イメージ説明

投稿2018/12/06 09:12

編集2018/12/12 04:53
退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

blackdifferent

2018/12/07 00:36

回答いただきありがとうございます。 onclick="location.href='@Url.Action("BtnClick","Kintai")'" はボタンを引数のコントローラアクションを呼ぶものですが、おっしゃるようにJavaScript / jQueryで書くのが良さそうに思います。 JavaScriptを書いた経験が全くないので、よければ具体的なコードを教えていただけないでしょうか?
退会済みユーザー

退会済みユーザー

2018/12/07 01:24 編集

自力で実装してみて分からないところを聞くようにしていただければと思います。上の回答で書いたようにして間違いなくできます、それをどのようにコードに落とし込むかということだけで、決して難しくはないです。
blackdifferent

2018/12/07 05:59 編集

一応やりたかった機能は実装出来ました。ボタン機能のとこだけコードを載せます。 ビュー: <button type="button" onclick="location.href='@Url.Action("Index","TKintais",new { id = Model[idx].id - 1})'">定時</button> コントローラ: public ActionResult Index(int? id) { List<TKintai> kintais = db.TKintai.ToList(); if (id != null) { kintais[Int32.Parse(id.ToString())].open = TimeSpan.FromHours(9); kintais[Int32.Parse(id.ToString())].close = TimeSpan.FromHours(18); kintais[Int32.Parse(id.ToString())].rest = TimeSpan.FromHours(1); } //選択ボックスのオプションを準備 List<TSituation> situations = db.TSituation.ToList(); Dictionary<int, SelectList> dictionary = new Dictionary<int, SelectList>(); foreach (TSituation item in situations) { dictionary.Add(item.id, new SelectList(situations, "ID", "Situation", item.id)); } ViewBag.Situation = dictionary; return View(kintais); } しかし定時ボタンを押したときに編集中のデータが消えてしまうという問題点があります。 もう少し良いやり方がないか考えてみたいと思います。
退会済みユーザー

退会済みユーザー

2018/12/07 07:33

JavaScript 案はボツでしょうか? テキストボックスにユーザーが 9:00, 18:00 と入力するのをボタンクリック一発で済ませたいということだけで、サーバー側でのアクションメソッドでの処理は必要ないのでは? そうだとすると、上の質問者さんのコードは非常に無駄なサーバー側でのリソースの浪費になるように思うのですが・・・
blackdifferent

2018/12/07 08:55

そうですね。JavaScriptでクライアント側だけで処理を行う方法を考えていました。 しかしJavaScriptの知識が全くないので、少し勉強してから実装を考えようかと思います。
退会済みユーザー

退会済みユーザー

2018/12/08 05:50

JavaScript でテキストボックスに 9:00, 18:00 という値を設定する方法は「javascript」「value」「設定」などをキーワードにググると参考になる記事が多々ヒットすると思います。 問題は当該テキストボックスの id の取得だと思いますが、Html ヘルパーの IdFor メソッド利用すれば可能です。以下の記事を参考にしてください。 Control.ClientID と Html.IdFor http://surferonwww.info/BlogEngine/post/2017/02/19/control-clientid-and-html-idfor.aspx
退会済みユーザー

退会済みユーザー

2018/12/11 08:46

JavaScript 案は結局ボツですか?
blackdifferent

2018/12/11 11:36

すみません。 今先にデータベース関連のほうをやってまして、一時保留にしてます。 あとで必ずやります。
blackdifferent

2018/12/12 05:10

ありがとうございます。出来ました。 全く分かんない状態で聞くのも申し訳なかったので、勉強してからにしようと思ってたのですが... 今後勉強していきたいと思います。
blackdifferent

2018/12/25 08:19

解決済みの質問ですみません。 この質問の回答で定時ボタンを押したときに、"9:00""18:00"という値を入れたと思いますが、これを文字列でなくTimeSpan型のモデル(@Model.PersonalInfo.ordinary_open)の値を入れる方法を教えていただけますか? .ToString("hh':'mm':'ss")など試してみましたが、なにも表示されませんでした。
退会済みユーザー

退会済みユーザー

2018/12/25 09:31

> TimeSpan型のモデル(@Model.PersonalInfo.ordinary_open)の値 (@Model.PersonalInfo.ordinary_open) って何ですか? 初めて出てきましたよね。 基本的なやり方がかなり変わってくるはずなので、新たに別のスレッドを立てて、そのあたりの説明から始めて、質問願います。
blackdifferent

2018/12/25 23:57

分かりました。 新しいスレッドに質問させていただきます。
guest

0

始業時刻のViewにclass追加
@Html.EditorFor(model => model[idx].open, new { htmlAttributes = new { @class = "form-control start_time" } })
終業時刻にもclass追加
@Html.EditorFor(model => model[idx].open, new { htmlAttributes = new { @class = "form-control end_time" } })
定時ボタンにもclass追加(onclickは削除)
<button type="button" class ="teizi">定時</button>

<script> $(function(){ $(document).on('click','button.teizi',function () { $(this).closest('tr').find('input.start_time').val('09:00:00') $(this).closest('tr').find('input.end_time').val('18:00:00') }) }) </script>

もつとシャープな方法/書き方があるかと思いますが、
多分これで動きます

投稿2018/12/12 02:43

編集2018/12/12 02:45
tkta

総合スコア21

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2018/12/12 02:50

> もつとシャープな方法/書き方があるかと思いますが、 あります。当該テキストボックスの id の取得に Html ヘルパー IdFor の利用を考えてみてください。MVC4 なのですから使えます。
tkta

2018/12/12 03:00

なるほど、クラスではなく、IdForを追加すればいいのですね お恥ずかしながら、使用したことありませんでした。。。 新たな知識を得れてよかったです。ありがとうございます
tkta

2018/12/12 03:00

IdForのほうが、ASP.NETMVC5らしくていいですね
tkta

2018/12/12 03:01

4でした、すみません。。。
blackdifferent

2018/12/12 04:16

すみません。ほぼそのまま使用してみたのですがボタンを押しても何も起こりませんでした。 デバッグしましたが、Script文自体が呼ばれていないようです。 Script文を、<button type="button" class ="teizi">定時</button> のすぐ後に置いたのですが、よろしかったでしょうか?
退会済みユーザー

退会済みユーザー

2018/12/12 04:27

> 少し勉強してから実装を考えようかと思います ということだったはずですが・・・ 迷走しそうなので、後で私の回答欄にサンプルを書いておきます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問