Controller

基本概念

最基本的Controller,跟Spring不一樣的是,Spring利用@Controller去表示這個類別是個Controller,在ASP.net MVC是以繼承Controller來表示。在ASP.net MVC中,return的內容就是html,在Spring則必須利用@ResponseBody,來指定return的內容是html。

using System.Web;
using System.Web.Mvc; 
 
namespace MvcMovie.Controllers 
{ 
    public class HelloWorldController : Controller 
    { 
        // 
        // GET: /HelloWorld/ 
 
        public string Index() 
        { 
            return "This is my <b>default</b> action..."; 
        } 
 
        // 
        // GET: /HelloWorld/Welcome/ 
 
        public string Welcome() 
        { 
            return "This is the Welcome action method..."; 
        } 
    } 
}

與View的互動

在ASP.net MVC裡,如果要去呼叫一個view,回傳值的資料型態是ActionResult,並且呼叫View。在ASP.net MVC中,Controller與View的對應是靠檔名 (事實上背後是依照rounting規則,當然,也可以指定打開哪個view),以下面的Controller為例,會去呼叫Views底下的HelloWorld(Controller的名稱)資料夾下的Index.cshtml(方法的名稱)。

using System.Web;
using System.Web.Mvc; 
 
namespace MvcMovie.Controllers 
{ 
    public class HelloWorldController : Controller 
    { 
        // 
        // GET: /HelloWorld/ 
 
        public ActionResult Index() 
        { 
            return View(); 
        } 
 
        // 
        // GET: /HelloWorld/Welcome/ 
 
        public string Welcome() 
        { 
            return "This is the Welcome action method..."; 
        } 
    } 
}

參數傳遞

在ASP.net MVC裡,可以直接接收變數,當利用「http://localhost:xx/HelloWorld/Welcome?name=Scott&numtimes=4」來呼叫這個方法時,name的內容就是「Scott」,numTimes的內容就是「4」,也可以給預設值,如: numTimes的預設值就是「1」。也可以使用預設的ViewBag來傳變數給view。

using System.Web;
using System.Web.Mvc;

namespace MvcMovie.Controllers
{
    public class HelloWorldController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Welcome(string name, int numTimes = 1)
        {
            ViewBag.Message = "Hello " + name;
            ViewBag.NumTimes = numTimes;

            return View();
        }
    }
}

參考資料