iT邦幫忙

2021 iThome 鐵人賽

DAY 9
1
自我挑戰組

.NET Core MVC網頁應用開發系列 第 9

.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; }
    }
}

https://ithelp.ithome.com.tw/upload/images/20210909/20107452tBzw1LIWIg.png

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檢視)
https://ithelp.ithome.com.tw/upload/images/20210909/201074521KuHRnmYjV.png

預設檢視名稱已自動選好為Index
https://ithelp.ithome.com.tw/upload/images/20210909/201074528v2VUsfBG4.png

調整引入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>

執行後正常把資料群陳列出來

https://ithelp.ithome.com.tw/upload/images/20210909/20107452OkUs127qBT.png

本篇已同步發表至個人部落格
https://coolmandiary.blogspot.com/2021/07/net-core9mvcmodel.html


上一篇
.NET Core第8天_路由端點的切換_注入MVC服務_利用middleware來啟用靜態資源設置預設網址路由
下一篇
.NET Core第10天_搭配EF Core串聯資料庫Db First_使用EntityFramework執行檢視的MVC控制器
系列文
.NET Core MVC網頁應用開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言