1.1.4.Add a new Model, Controller, View

1.Add a new model class

  • Model主要是具備與問題有關的property以表示物件的state, 而不會有運算邏輯

      public class Movie
      {
          public int Id { get; set; }
          public string Name { get; set; }
      }

2.Add a new Controller

  • 在Controller資料夾下面新增一個MoviesController.cs時, Views資料夾下也會自動新增一個Movies資料夾, 當MoviesController.cs下的某一個ActionResult回傳了View()時, 就會到Views/Movies下面尋找對應的.cshtml

  • 在MoviesController.cs的Random()內新增一個Movie物件並放入View()中, 建立model跟view的binding

      // GET: Movies/Random
      public ActionResult Random()
      {
          var movie = new Movie() { Name = "Shrek" };
          return View(viewModel);
      }

3.Add a new View

  • @Model預設是dynamic, 因此無法抓到model下的property, 必須先指定model是哪個檔案

    model Vidly2.Models.Movies
    @{
        ViewBag.Title = "Random";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }

    <h2 class = "@className">@Model.Name</h2>
  • 可以到bootswatch下載不一樣的bootstrap.css並放到/Content底下

  • 修改/App_Start/BundleConfig.cs

4.Build and Run

  • Open browser and type url : movie/random

Last updated