1. 程式人生 > >(1) Controllers [ 教學 ] (使用visual studio) « 關於網路那些事...

(1) Controllers [ 教學 ] (使用visual studio) « 關於網路那些事...

Model-View-Controller (MVC) 根據維基百科解釋

MVC模式(Model–view–controller)是軟體工程中的一種軟體架構模式,把軟體系統分為三個基本部分:模型(Model)、檢視(View)和控制器(Controller)。

使用MVC的方式來建構應用程式,可以讓程式容易維護、更新及測試。
其中,它們各自分別負責的任務如下:

模型(Model)
負責操控資料庫,並提供給Controller
檢視(View)
負責建構使用者介面(UI),將資料內容呈現出來。
控制器(Controller)
負責處理HTTP請求、從Model取回指定的資料,並且可以將資料傳送給指定的View

一、檢視專案的 MVC 資料架構

開啟新建立專案後,從右側欄位可以發現 controllers、views、Models

如果沒有 Models 資料夾
原因可能是在新增專案時,忘了選擇 Individual User Accounts
可以參考之前的說明

二、 Controllers 基本介紹

在controllers資料夾>右鍵>Add>New item

並且在對話視窗中,輸入Controllers名稱
命名規則是 你的名稱+Controller.cs

新增完畢後,就可以直接在 controllers 資料夾看到新增的 HelloworldController.cs

開啟檔案,修改內容:
Controllers/HelloworldController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace WebApplication2.Controllers
{ public class HelloWorldController : Controller { // GET: /<controller>/ public string Index() { return "Hello world主畫面s"; } public string Detail() { return "細節畫面"; } } }

從Controllers 接收 HTTP Request
修改controllers內容
引用 System.Text.Encodings.Web; 以及調整 welcome 內容
在這裡要接收name及unmTimes引數,並且用到HtmlEncoder.Default.Encode來避免表單輸入攻擊。
(如果沒有 using System.Text.Encodings.Web , 執行時會出現錯誤訊息: The name 'HtmlEncoder' does not exist in the current context)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace WebApplication2.Controllers
{
    public class HelloWorldController : Controller
    {
        // GET: /<controller>/
        public string Index()
        {
            return "Hello world主畫面";
        }

        public string Detail()
        {
            return "This is Detail page!";
        }

        public string Welcome(string name, int numTimes = 1)
        {
            return HtmlEncoder.Default.Encode($"Hello {name}, numTimes: {numTimes}");
            /*
            當然,你也可以直接呼叫
            return $"Hi {name} and num: {numTimes}";
            */
        }


    }
}

預覽結果:

Hello Adam, numTimes: 2

變更 ASP.NET Core MVC 預設畫面
ASP.NET Core MVC Web app 安裝的範例專案
預設畫面會指向 HomeController (Home)
現在我們來將預設畫面調整至剛剛新增的 HelloworldController

首先開啟 Startup.cs

在檔案底部會看到

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

將內容調整為,就可以成功變更調預設的首頁畫面

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=HelloWorld}/{action=Index}/{id?}");
        });

參考:


如果你喜歡我們的文章內容,請在這裡按個讚