Mvc-framework-advanced-example

提供:Dev Guides
移動先:案内検索

MVCフレームワーク-高度な例

最初の章では、MVCでコントローラーとビューがどのように相互作用するかを学びました。 このチュートリアルでは、モデルを使用して、作成、編集、削除する高度なアプリケーションを作成する方法を学びます。 アプリケーションのユーザーのリストを表示します。

高度なMVCアプリケーションを作成する

  • ステップ1 *-[ファイル]→[新規]→[プロジェクト]→[ASP.NET MVC Webアプリケーション]を選択します。 AdvancedMVCApplicationという名前を付けます。 Okをクリックしてください。 次のウィンドウで、「インターネットアプリケーションとしてのテンプレート」と「Razorとしてのビューエンジン」を選択します。 今回は空のアプリケーションの代わりにテンプレートを使用していることに注意してください。

MVC New Internet Project

これにより、次のスクリーンショットに示すように、新しいソリューションプロジェクトが作成されます。 デフォルトのASP.NETテーマを使用しているため、サンプルビュー、コントローラー、モデル、その他のファイルが付属しています。

MVC Model View Controller

  • ステップ2 *-ソリューションをビルドし、アプリケーションを実行して、次のスクリーンショットに示すデフォルト出力を確認します。

MVCサンプルインターネットアプリケーション

  • ステップ3 *-ユーザーデータの構造を定義する新しいモデルを追加します。 Modelsフォルダーを右クリックして、追加→クラスをクリックします。 これにUserModelという名前を付け、[追加]をクリックします。

MVCモデルの追加ステップ1

MVCモデルの追加ステップ2

  • ステップ4 *-新しく作成されたUserModel.csに次のコードをコピーします。
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc.Html;

namespace AdvancedMVCApplication.Models {
   public class UserModels {

      [Required]
      public int Id { get; set; }
      [DisplayName("First Name")]
      [Required(ErrorMessage = "First name is required")]
      public string FirstName { get; set; }
      [Required]
      public string LastName { get; set; }

      public string Address { get; set; }

      [Required]
      [StringLength(50)]
      public string Email { get; set; }

      [DataType(DataType.Date)]
      public DateTime DOB { get; set; }

      [Range(100,1000000)]
      public decimal Salary { get; set; }
   }
}

上記のコードでは、Userモデルに含まれるすべてのパラメーター、データ型、必須フィールドや長さなどの検証を指定しました。

ユーザーモデルにデータを保持する準備ができたので、クラスファイルUsers.csを作成します。このファイルには、ユーザーの表示、ユーザーの追加、編集、削除のメソッドが含まれます。

  • ステップ5 *-モデルを右クリックして、追加→クラスをクリックします。 ユーザーとして名前を付けます。 これにより、Models内にusers.csクラスが作成されます。 users.csクラスの次のコードをコピーします。
using System;
using System.Collections.Generic;
using System.EnterpriseServices;

namespace AdvancedMVCApplication.Models {

   public class Users {
      public List UserList = new List();

     //action to get user details
      public UserModels GetUser(int id) {
         UserModels usrMdl = null;

         foreach (UserModels um in UserList)

            if (um.Id == id)
               usrMdl = um;
               return usrMdl;
      }

     //action to create new user
      public void CreateUser(UserModels userModel) {
         UserList.Add(userModel);
      }

     //action to udpate existing user
      public void UpdateUser(UserModels userModel) {

         foreach (UserModels usrlst in UserList) {

            if (usrlst.Id == userModel.Id) {
               usrlst.Address = userModel.Address;
               usrlst.DOB = userModel.DOB;
               usrlst.Email = userModel.Email;
               usrlst.FirstName = userModel.FirstName;
               usrlst.LastName = userModel.LastName;
               usrlst.Salary = userModel.Salary;
               break;
            }
         }
      }

     //action to delete exising user
      public void DeleteUser(UserModels userModel) {

         foreach (UserModels usrlst in UserList) {

            if (usrlst.Id == userModel.Id) {
               UserList.Remove(usrlst);
               break;
            }
         }
      }
   }
}

UserModel.csとUsers.csを取得したら、ユーザーの表示、ユーザーの追加、編集、削除のためのビューをモデルに追加します。 まず、ビューを作成してユーザーを作成します。

  • ステップ6 *-Viewsフォルダーを右クリックし、Add→Viewをクリックします。

mvc_advanced_add_view

  • ステップ7 *-次のウィンドウで、ビュー名をUserAdd、ビューエンジンをRazorとして選択し、[厳密に型指定されたビューを作成]チェックボックスを選択します。

MVC Advanced User Add View

  • ステップ8 *-[追加]をクリックします。 これにより、以下に示すように、デフォルトで次のCSHMLコードが作成されます-
@model AdvancedMVCApplication.Models.UserModels

@{
   ViewBag.Title = "UserAdd";
}

<h2>UserAdd</h2>

@using (Html.BeginForm()) {
   @Html.ValidationSummary(true)

   <fieldset>
      <legend>UserModels</legend>
      <div class = "editor-label">
         @Html.LabelFor(model => model.FirstName)
      </div>

      <div class = "editor-field">
         @Html.EditorFor(model => model.FirstName)
         @Html.ValidationMessageFor(model => model.FirstName)
      </div>

      <div class = "editor-label">
         @Html.LabelFor(model => model.LastName)
      </div>

      <div class = "editor-field">
         @Html.EditorFor(model => model.LastName)
         @Html.ValidationMessageFor(model => model.LastName)
      </div>

      <div class = "editor-label">
         @Html.LabelFor(model => model.Address)
      </div>

      <div class = "editor-field">
         @Html.EditorFor(model => model.Address)
         @Html.ValidationMessageFor(model => model.Address)
      </div>

      <div class = "editor-label">
         @Html.LabelFor(model => model.Email)
      </div>

      <div class = "editor-field">
         @Html.EditorFor(model => model.Email)
         @Html.ValidationMessageFor(model => model.Email)
      </div>

      <div class = "editor-label">
         @Html.LabelFor(model => model.DOB)
      </div>

      <div class = "editor-field">
         @Html.EditorFor(model => model.DOB)
         @Html.ValidationMessageFor(model => model.DOB)
      </div>

      <div class = "editor-label">
         @Html.LabelFor(model => model.Salary)
      </div>

      <div class = "editor-field">
         @Html.EditorFor(model => model.Salary)
         @Html.ValidationMessageFor(model => model.Salary)
      </div>

      <p>
         <input type = "submit" value = "Create"/>
      </p>
   </fieldset>
}
<div>
   @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {

   @Scripts.Render("~/bundles/jqueryval")
}

ご覧のとおり、このビューには、検証メッセージ、ラベルなど、フィールドのすべての属性の詳細が表示されます。 このビューは、最終アプリケーションでは次のようになります。

MVC Advanced Application 1

UserAddと同様に、指定されたコードで以下に示す4つのビューを追加します-

Index.cshtml

このビューには、システムに存在するすべてのユーザーが[インデックス]ページに表示されます。

@model IEnumerable<AdvancedMVCApplication.Models.UserModels>

@{
   ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
   @Html.ActionLink("Create New", "UserAdd")
</p>

<table>
   <tr>
      <th>
         @Html.DisplayNameFor(model => model.FirstName)
      </th>

      <th>
         @Html.DisplayNameFor(model => model.LastName)
      </th>

      <th>
         @Html.DisplayNameFor(model => model.Address)
      </th>

      <th>
         @Html.DisplayNameFor(model => model.Email)
      </th>

      <th>
         @Html.DisplayNameFor(model => model.DOB)
      </th>

      <th>
         @Html.DisplayNameFor(model => model.Salary)
      </th>

      <th></th>
   </tr>

   @foreach (var item in Model) {
      <tr>
         <td>
            @Html.DisplayFor(modelItem => item.FirstName)
         </td>

         <td>
            @Html.DisplayFor(modelItem => item.LastName)
         </td>

         <td>
            @Html.DisplayFor(modelItem => item.Address)
         </td>

         <td>
            @Html.DisplayFor(modelItem => item.Email)
         </td>

         <td>
            @Html.DisplayFor(modelItem => item.DOB)
         </td>

         <td>
            @Html.DisplayFor(modelItem => item.Salary)
         </td>

         <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
            @Html.ActionLink("Details", "Details", new { id = item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.Id })
         </td>
      </tr>
   }
</table>

このビューは、最終アプリケーションでは次のようになります。

MVC Advanced Application 2

Details.cshtml

このビューには、ユーザーレコードをクリックすると、特定のユーザーの詳細が表示されます。

@model AdvancedMVCApplication.Models.UserModels

@{
   ViewBag.Title = "Details";
}

<h2>Details</h2>
<fieldset>
   <legend>UserModels</legend>
   <div class = "display-label">
      @Html.DisplayNameFor(model => model.FirstName)
   </div>

   <div class = "display-field">
      @Html.DisplayFor(model => model.FirstName)
   </div>

   <div class = "display-label">
      @Html.DisplayNameFor(model => model.LastName)
   </div>

   <div class = "display-field">
      @Html.DisplayFor(model => model.LastName)
   </div>

   <div class = "display-label">
      @Html.DisplayNameFor(model => model.Address)
   </div>

   <div class = "display-field">
      @Html.DisplayFor(model => model.Address)
   </div>

   <div class = "display-label">
      @Html.DisplayNameFor(model => model.Email)
   </div>

   <div class = "display-field">
      @Html.DisplayFor(model => model.Email)
   </div>

   <div class = "display-label">
      @Html.DisplayNameFor(model => model.DOB)
   </div>

   <div class = "display-field">
      @Html.DisplayFor(model => model.DOB)
   </div>

   <div class = "display-label">
      @Html.DisplayNameFor(model => model.Salary)
   </div>

   <div class = "display-field">
      @Html.DisplayFor(model => model.Salary)
   </div>

</fieldset>
<p>
   @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
   @Html.ActionLink("Back to List", "Index")
</p>

このビューは、最終アプリケーションでは次のようになります。

MVC Advanced Application Details

Edit.cshtml

このビューには、既存のユーザーの詳細を編集するための編集フォームが表示されます。

@model AdvancedMVCApplication.Models.UserModels

@{
   ViewBag.Title = "Edit";
}

<h2>Edit</h2>
@using (Html.BeginForm()) {
   @Html.AntiForgeryToken()
   @Html.ValidationSummary(true)

   <fieldset>
      <legend>UserModels</legend>
      @Html.HiddenFor(model => model.Id)
      <div class = "editor-label">
         @Html.LabelFor(model => model.FirstName)
      </div>

      <div class = "editor-field">
         @Html.EditorFor(model => model.FirstName)
         @Html.ValidationMessageFor(model => model.FirstName)
      </div>

      <div class = "editor-label">
         @Html.LabelFor(model => model.LastName)
      </div>

      <div class = "editor-field">
         @Html.EditorFor(model => model.LastName)
         @Html.ValidationMessageFor(model => model.LastName)
      </div>

      <div class = "editor-label">
         @Html.LabelFor(model => model.Address)
      </div>

      <div class = "editor-field">
         @Html.EditorFor(model => model.Address)
         @Html.ValidationMessageFor(model => model.Address)
      </div>

      <div class = "editor-label">
         @Html.LabelFor(model => model.Email)
      </div>

      <div class = "editor-field">
         @Html.EditorFor(model => model.Email)
         @Html.ValidationMessageFor(model => model.Email)
      </div>

      <div class = "editor-label">
         @Html.LabelFor(model => model.DOB)
      </div>

      <div class = "editor-field">
         @Html.EditorFor(model => model.DOB)
         @Html.ValidationMessageFor(model => model.DOB)
      </div>

      <div class = "editor-label">
         @Html.LabelFor(model => model.Salary)
      </div>

      <div class = "editor-field">
         @Html.EditorFor(model => model.Salary)
         @Html.ValidationMessageFor(model => model.Salary)
      </div>

      <p>
         <input type = "submit" value = "Save"/>
      </p>
   </fieldset>
}
<div>
   @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
   @Scripts.Render("~/bundles/jqueryval")
}

このビューは、アプリケーションでは次のようになります。

MVC Advanced Application Details

Delete.cshtml

このビューには、既存のユーザーを削除するためのフォームが表示されます。

@model AdvancedMVCApplication.Models.UserModels

@{
   ViewBag.Title = "Delete";
}

<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<fieldset>
   <legend>UserModels</legend>
   <div class = "display-label">
      @Html.DisplayNameFor(model => model.FirstName)
   </div>

   <div class = "display-field">
      @Html.DisplayFor(model => model.FirstName)
   </div>

   <div class = "display-label">
      @Html.DisplayNameFor(model => model.LastName)
   </div>

   <div class = "display-field">
      @Html.DisplayFor(model => model.LastName)
   </div>

   <div class = "display-label">
      @Html.DisplayNameFor(model => model.Address)
   </div>

   <div class = "display-field">
      @Html.DisplayFor(model => model.Address)
   </div>

   <div class = "display-label">
      @Html.DisplayNameFor(model => model.Email)
   </div>

   <div class = "display-field">
      @Html.DisplayFor(model => model.Email)
   </div>

   <div class = "display-label">
      @Html.DisplayNameFor(model => model.DOB)
   </div>

   <div class = "display-field">
      @Html.DisplayFor(model => model.DOB)
   </div>

   <div class = "display-label">
      @Html.DisplayNameFor(model => model.Salary)
   </div>

   <div class = "display-field">
      @Html.DisplayFor(model => model.Salary)
   </div>
</fieldset>

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

   <p>
      <input type = "submit" value = "Delete"/> |
      @Html.ActionLink("Back to List", "Index")
   </p>
}

このビューは、最終アプリケーションでは次のようになります。

MVC詳細アプリケーション詳細削除

  • ステップ9 *-すでにアプリケーションにモデルとビューを追加しています。 最後に、ビューにコントローラーを追加します。 Controllersフォルダーを右クリックして、Add→Controllerをクリックします。 UserControllerという名前を付けます。

MVC Advanced Add Controller

デフォルトでは、コントローラクラスは次のコードで作成されます-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AdvancedMVCApplication.Models;

namespace AdvancedMVCApplication.Controllers {

   public class UserController : Controller {
      private static Users _users = new Users();

      public ActionResult Index() {
         return View(_users.UserList);
      }
   }
}

上記のコードでは、IndexページでユーザーのリストをレンダリングするときにIndexメソッドが使用されます。

  • ステップ10 *-インデックスメソッドを右クリックし、[ビューの作成]を選択して、インデックスページのビューを作成します(すべてのユーザーがリストされ、新しいユーザーを作成するオプションが表示されます)。

MVC高度なインデックスビューの追加

  • ステップ11 *-次のコードをUserController.csに追加します。 このコードでは、さまざまなユーザーアクションのアクションメソッドを作成し、前に作成した対応するビューを返します。

操作ごとに、GETとPOSTの2つのメソッドを追加します。 HttpGetは、データを取得してレンダリングするときに使用されます。 HttpPostは、データの作成/更新に使用されます。 たとえば、新しいユーザーを追加する場合、ユーザーを追加するフォームが必要になります。これはGET操作です。 フォームに入力してこれらの値を送信したら、POSTメソッドが必要になります。

//Action for Index View
public ActionResult Index() {
   return View(_users.UserList);
}

//Action for UserAdd View
[HttpGet]
public ActionResult UserAdd() {
   return View();
}

[HttpPost]
public ActionResult UserAdd(UserModels userModel) {
   _users.CreateUser(userModel);
   return View("Index", _users.UserList);
}

//Action for Details View
[HttpGet]
public ActionResult Details(int id) {
   return View(_users.UserList.FirstOrDefault(x => x.Id == id));
}

[HttpPost]
public ActionResult Details() {
   return View("Index", _users.UserList);
}

//Action for Edit View
[HttpGet]
public ActionResult Edit(int id) {
   return View(_users.UserList.FirstOrDefault(x=>x.Id==id));
}

[HttpPost]
public ActionResult Edit(UserModels userModel) {
   _users.UpdateUser(userModel);
   return View("Index", _users.UserList);
}

//Action for Delete View
[HttpGet]
public ActionResult Delete(int id) {
   return View(_users.UserList.FirstOrDefault(x => x.Id == id));
}

[HttpPost]
public ActionResult Delete(UserModels userModel) {
   _users.DeleteUser(userModel);
   return View("Index", _users.UserList);
} sers.UserList);
  • ステップ12 *-最後に行うことは、App_StartフォルダーのRouteConfig.csファイルに移動し、デフォルトのコントローラーをユーザーに変更することです。
defaults: new { controller = "User", action = "Index", id = UrlParameter.Optional }

高度なアプリケーションを起動して実行するために必要なのはそれだけです。

  • ステップ13 *-アプリケーションを実行します。 次のスクリーンショットに示すように、アプリケーションを見ることができます。 前のスクリーンショットで見たように、ユーザーの追加、表示、編集、削除のすべての機能を実行できます。

MVC Advanced Add Index Final