.NET Core第9天_MVC_Model的引入
在上一篇我們已經知道MVC路由和靜態資源導入的方式
因此起手式
從新增專案.net core空專案到注入MVC服務跟設置預設MVC路由這塊就省略
我們新增Models的目錄並新增model class 員工(Employee),分別有編號、姓名、工作年資。
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace prjNet5_3.Models { public class Employee { public string Id { get; set; } public string Name { get; set; } public int WorkYear { get; set; } } }
Controllers目錄跟Home控制器創建好後
引入員工物件列表(在此用IList來裝載)
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using prjNet5_3.Models; namespace prjNet5_3.Controllers { public class HomeController : Controller { IList<Employee> employees = new List<Employee>(); public IActionResult Index() { employees.Add(new Employee { Id = "E001", Name = "林曉華", WorkYear = 3 }); employees.Add(new Employee { Id = "E002", Name = "黃群芳", WorkYear = 1 }); employees.Add(new Employee { Id = "E003", Name = "陳紋梅", WorkYear = 5 }); return View(employees); } } }
在去新增檢視(選擇Razor檢視)
預設檢視名稱已自動選好為Index
調整引入Model後的Index.cshtml
@model IEnumerable<prjNet5_3.Models.Employee> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> @foreach(var item in Model) { <div> <p>編號:@item.Id</p> <p>姓名:@item.Name</p> <p>年資:@item.WorkYear</p> </div> } </body> </html>
執行後正常把資料群陳列出來
留言
張貼留言