ASP.NET MVC第003天_Model跟View之間透過Controller的互動

 MVC中的Model資料操作都會在此操作
這裡新增額外的控制器EShopController



在Model  folder新建一個一般的class

比如user


User.cs

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

namespace MyEmptyMVC1.Models
{
    public class User
    {
        string name;
        int age;

        public string Name { get => name; set => name = value; }
        public int Age { get => age; set => age = value; }
    }
}


修改好Controller中的Action添加完畢View

EShopController.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using MyEmptyMVC1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyEmptyMVC1.Controllers
{
    public class EShopController : Controller
    {
        // GET: EShop
        public ActionResult Index()
        {
            User usr = new User();
            usr.Name = "Kevin";
            usr.Age = 28;
            List<User> lsUsr = new List<User>();
            lsUsr.Add(usr);
            return View(lsUsr);
        }
    }
}

接著介紹要在View裡面引入Model的方式
是透過
@using Model文件命名空間
@model IEnumerable<特定類別>

呈現資料方式可能包覆html 一些清單tag....
<ul>
    @foreach(特定物件類別 xx in Model)
    {
        
    }
</ul>

Index  檢視程式碼

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@{
    Layout = null;
}

@using MyEmptyMVC1.Models;
@model IEnumerable<User>

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        @foreach(User usr in Model) 
        {
            <li>@usr.Name</li>
        }
    </div>
</body>
</html>

最終執行效果
這就是一個簡單的View 例子









留言

這個網誌中的熱門文章

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

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

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