Part2 -> Section1 The Basic -> 005. Controller

     MVC , C คือ Controller ซึ่ง Controller ก็คือ class ที่สืบทอดมาจาก class System.Web.Mvc.Controller ภายใน Controller จะมี Action method
     Controller และ Action method ทำหน้าที่จัดการ request ต่างที่เข้ามา, ติดต่อแลกเปลี่ยนข้อมูลกับ model และส่งค่ากลับให้ browser
     สำหรับ ASP.NET MVC นั้น ทุกๆ controller จะต้องต่อท้ายด้วย "Controller" ตัวอย่างเช่น controller สำหรับ home page จะเป็น "HomeController" และ controller จะต้องอยู่ใน Controller folder

เริ่มสร้าง Controller
     ในตัวอย่างนี้เราจะสร้าง controller student โดยเริ่มต้นที่ คลิกขวาที่ folder "Controllers" => Add => Controller...
   ใส่ Student ใน dialog
     โปรแกรมจะสร้าง controller class ให้ดังโค้ดด้านล่าง

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVC_Tutorial_2_1.Controllers
{
    public class StudentController : Controller
    {
        //
        // GET: /Student/

        public ActionResult Index()
        {
            return View();
        }

    }
}

แก้ไข Action method โดยแก้ไข return type เป็น string และ return wording ตามด้านล่าง (return type ActionResult จะได้ศึกษาในตอนต่อๆไปครัช)
public string Index()
{
     return "This is Index from StudentController";
}

ทำการ run เว็บขึ้นมาโดยกด Ctrl+F5 browser จะรันหน้าเว็บ home ขึ้นมา

เปลี่ยน url โดยให้ระบุ controller Student ลงไป จะได้ผลดังรูป
ข้อสักเกตุ 1 ถ้าไม่ระบุ Controller จะหมายถึง home controller นั่นแสดงว่าในตอนที่เรา run เว็บขึ้นมาครั้งแรกนั้น (หน้าเว็บสวยๆด้านบนน่ะคับ) ก็คือ home controller นั่นเอง
ข้อสังเกตุ 2 ถ้าไม่ระบุ Action method จะหมายถึงโปรแกรมจะไปเรียกใช้ Action method Index นั่นหมายความว่า /student และ /student/index นั้นมีค่าเท่ากัน ลองดูครัช

สอบถามหรือติดตามได้ที่ https://www.facebook.com/learnaspnetmvcjquery

ความคิดเห็น

โพสต์ยอดนิยมจากบล็อกนี้

Part2 -> Section1 The Basic -> 003. MVC Folder Structure

Part2 -> Section1 The Basic -> 001. Introduction

สารบัญ (Table of content)