全て
| カテゴリ未分類
| 通常
| 数学
| 投資
| 副業
| 転職・就職
| ブログ
| 株Stock
| VBA
| SharePoint
| REST API
| RenderListDataAsStream
| PowerAutomateDesktop
| Graph API
| PowerApps
| PowerAutomate
| PowerFx
| OfficeScriptオフィススクリプト
| PowerAutomate日時Excel日時相互関係
| PowerShell
| Dataverse
| UiPath
| OneDrive
| LINQ
| VB.NET
| C#.NET
| WPFC#.NET
| Git
| ネットワーク
| Azure
| AWS
| JP1
| セキュリティ
| JavaScript
| Google Cloud
カテゴリ:C#.NET
以下は、ASP.NET MVC パターンでデータを新規追加するサンプルコードです。 まず、モデルを定義します。 ```csharp using System.ComponentModel.DataAnnotations; namespace MvcAddExample.Models { public class Item { public int Id { get; set; } [Required] public string Name { get; set; } } } ``` 次に、コントローラーを作成します。 ```csharp using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using MvcAddExample.Models; namespace MvcAddExample.Controllers { public class ItemController : Controller { private static readonly List<Item> items = new List<Item> { new Item { Id = 1, Name = "Item 1" }, new Item { Id = 2, Name = "Item 2" }, new Item { Id = 3, Name = "Item 3" } }; // 一覧表示アクション public ActionResult Index() { return View(items); } // 新規追加画面表示アクション public ActionResult Create() { return View(); } // 追加アクション [HttpPost] public ActionResult Create(Item item) { if (ModelState.IsValid) { int newId = items.Max(i => i.Id) + 1; item.Id = newId; items.Add(item); return RedirectToAction("Index"); } return View(item); } } } ``` このコントローラーは、`Item` モデルの一覧表示、新規追加画面表示、データ追加を提供します。`Index` アクションは、`items` リストをビューに渡して表示します。`Create` アクションは、新規アイテムのフォームを表示します。`HttpPost` 属性が付いた `Create` アクションは、フォームから送信されたデータを受け取り、新しいアイテムをリストに追加して一覧ページにリダイレクトします。 最後に、ビューを作成します。 Index.cshtml: ```html @model IEnumerable<MvcAddExample.Models.Item> <table> <tr> <th>ID</th> <th>Name</th> </tr> @foreach (var item in Model) { <tr> <td>@item.Id</td> <td>@item.Name</td> </tr> } </table> @Html.ActionLink("Create New", "Create") ``` Create.cshtml: ```html @model MvcAddExample.Models.Item @using (Html.BeginForm()) { @Html.ValidationSummary(true) <div> @Html.LabelFor(model => model.Name) @Html.TextBoxFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <button type="submit">Create</button> } ``` このビューは、`Item` モデルの一覧を表示し、新規追加リンクを提供します。新規追加画面では、新しいアイテムの名前を入力し、作成ボタンをクリックすることでデータが追加されます。 このサンプルでは、MVC パターンの原則に従っています。ビューはユーザーインターフェイスを表示し、コントローラーはビジネスロジックを処理し、モデルはデータを表現します。 お気に入りの記事を「いいね!」で応援しよう
Last updated
2024.03.13 05:54:32
[C#.NET] カテゴリの最新記事
|