ASP.NET MVC第010天_Model介紹(2)_檢視接收多筆MVC Model資料

 



若要在View上呈現多筆資料
則可以
Step1.預期會有多筆的Model Class先設計好
這裡用的是一個CountryCity的Class

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MVCWebApp1.Models
{
    public class CountryCity
    {
        [Required]
        [Display(Name ="城市")]
        public string City { get; set; }
        [Required]
        [Display(Name ="國家")]
        public string Country { get; set; }
    }
}


Step2.
在Controller中可以去建立一個ActionResult 函數
返回一個會傳遞某Model陣列的View

1
2
3
4
5
6
7
public ActionResult CountryList()
        {
            CountryCity[] cities = new CountryCity[] { new CountryCity() { City = "台北市", Country = "中華民國台灣" },
                                                       new CountryCity() { City = "新北市", Country = "中華民國台灣" },
                                                       new CountryCity() { City = "新竹市", Country = "中華民國台灣" }};
            return View(cities);
        }



Step3.
建立一個新View挑選Scaffold List模板(因為有多筆)
在View上宣告@model 某物件陣列
由View將物件陣列傳入




預設CountryList.cshtml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
@model IEnumerable<MVCWebApp1.Models.CountryCity>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>CountryList</title>
</head>
<body>
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.City)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Country)
            </th>
            <th></th>
        </tr>
    
    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.City)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Country)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
            </td>
        </tr>
    }
    
    </table>
</body>
</html>


執行呈現效果

可以看到model藉由Razor引入至View使用時預設是透過IEnumerable的型態












留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients