
前提
ASP.NETを使用しています。
テキストボックスに文字を入れて検索ボタンを押すと、もともと表示されているSQLテーブルの品物カラムから一部検索でヒットしたものを表示したいと思っています。
データベースに接続し、index.cshtmlで一覧画面が表示されています。
実現したいこと
テキストボックスに文字を入れて検索ボタンを押すと、もともと表示されているSQLテーブルの品物カラムから一部検索でヒットしたものを表示したいと思っています。
発生している問題・エラーメッセージ
テキストボックスと検索ボタン
index.cshtml
<input type="text" name="textBox1"> <button OnClick="Button1_Click" name="Button1" id="Button1">検索</button>
該当のソースコード
SinamonoController
c#
1 //検索ボタン押下時 2 public ActionResult Button1_Click() 3 { 4 string ConnectionStr 5 = ConfigurationManager.ConnectionStrings["iPentecDBConnectionString"].ConnectionString; 6 7 SqlConnection connection; 8 connection = new SqlConnection(ConnectionStr); 9 connection.Open(); 10 11 //データベースに対して実行する指示を格納するクラス(上記オープンしたconnectionから生成[紐づけ]) 12 SqlCommand command = connection.CreateCommand(); 13 14 //コマンドのタイプをテキストで指定 15 command.CommandType = CommandType.Text; 16 17 //実行するSQLを設定 18 command.CommandText = "SELECT * FROM Bihin WHERE 品物 LIKE '%テキストボックスの値%'"; ; 19 20 //以下はSQL結果をDataTableに設定 21 SqlDataAdapter adapter = new SqlDataAdapter(); 22 DataTable dt = new DataTable(); 23 adapter.SelectCommand = command; 24 adapter.Fill(dt); 25 26 adapter = null; 27 command = null; 28 29 connection.Close(); 30 connection = null; 31 32 33 List<BihinDB> modelList = new List<BihinDB>(); 34 foreach (DataRow dr in dt.Rows) 35 { 36 modelList.Add(new BihinDB 37 { 38 BuppinName = dr["Sinamono"].ToString(), 39 ・・・ 40 }); 41 42 } 43 44 return View(modelList); 45 46 } 47 48 49 50 //テキストボックスの値を取得 51 public ActionResult Action1(string textbox) 52 { 53 // Viewに設定したnameと一致させることによってControllerで値を取得できる。 54 HttpContext.Session.Add("txt", textbox); 55 56 return RedirectToAction("");
ボタンをクリックしたときの処理をcontrollerに渡す方法、
テキストボックスの値を渡す方法、
SELECT文の中の”テキストボックスの値”の所はどのように書けばよいのか
教えていただきたいです。
試したこと
上記の検索ボタン押下時、テキストボックスの値の取得です。
①テキストボックスの値を取得
②ボタンクリック時のコードの中に、データベース接続をしてSELECT WHERE LIKE①を使って該当コードを表示させる
という方法で考えています。
補足情報(FW/ツールのバージョンなど)
ASP.NET MVC
Windows 10 Pro,
Visual Studio2022 Version 17.3.2
.NET framework 4.7.2
回答1件
あなたの回答
tips
プレビュー