iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 3
0
Modern Web

MVC概略與分享系列 第 3

[鐵人賽D3] Controller介紹與設定

前面有提過Controller是MVC架構中的C,主要是Model和View的橋樑。

一般如果要開始設計一個MVC的功能,我會先從建Controller開始,以VisuoStudio2017為例。

方案總管->加入->控制器(Controller)->MVC5控制器(空白) 即可完成Controller模板(cs檔)
https://ithelp.ithome.com.tw/upload/images/20181018/20111766nOwj6o9k6X.png

命名一個名稱為MyController會繼承Controller類別(參考官方文件)

public class MyController : Controller
{
    public ActionResult HelloWorld()
    {
        ViewData["Message"] = "Hello World!";
        return View();
    }
}

說明一下甚麼是ActionResult類別,同樣參考官方文件

    //
    // 摘要:
    //     Represents the result of an action method.
    public abstract class ActionResult
    {
        protected ActionResult();
        public abstract void ExecuteResult(ControllerContext context);
    }

ActionResult就是執行Action的结果。最後執行ExecuteResult方法,View是ActionResult的子類別ViewResult來完成的。ActionResult主要的幾個衍生類別如下:

https://ithelp.ithome.com.tw/upload/images/20181018/20111766KrFTOtpWVM.png

這邊介紹幾個我自己常用的:
FileResult
JsonResult

##FileResult
主要用於回傳檔案、檔案下載的時候

        public FileResult TestFileResult()
        {
            string excelPath = "C:\test.xlsx";
            return File(excelPath, "application/vnd.ms-excel", "Test.xlsx");
        }

##JsonResult
主要用於回傳前端ajax的請求時用

        public JsonResult TestJsonResult()
        {
            return Json(new { success = true, message = "成功!" }, "application/json");
        }

上一篇
[鐵人賽D2] Model介紹與設定
下一篇
[鐵人賽D4] View介紹與設定(1)
系列文
MVC概略與分享9
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言