MVC中的Controller

  Controller是MVC模式中的三个核心元素之一.

  MVC模式中的Controller主要负责响应用户的输入, 并在响应时修改Model.

  MVC提供的是方法调用的结果, 而不是动态生成的页面. 

  下面新建一个项目名为 MVC Music Store , 以此为例说明一下MVC中的Controller. 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 
 7 namespace MvcMusicStore.Controllers
 8 {
 9     public class HomeController : Controller
10     {
11         
12         public ActionResult Index()
13         {
        // 将默认内容修改为"I like cake!" 后即可直接显示在主页上.
14 ViewBag.Message = "I like cake!"; 15 return View(); 16 } 17 18 public ActionResult About() 19 { 20 ViewBag.Message = "Your app description page."; 21 22 return View(); 23 } 24 25 public ActionResult Contact() 26 { 27 ViewBag.Message = "Your contact page."; 28 29 return View(); 30 } 31 } 32 }

 HomeController 类的Index方法负责决定当浏览网站首页时触发的事件.

 

下面创建一个新的控制器并命名为 StoreController, 作如下修改:

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

namespace MvcMusicStore.Controllers
{
    public class StoreController : Controller
    {
        //
        // GET: /Store/

        public string Index()
        {
            return "Hello from Store.Index()";
        }

        //get: /Store/Browse
        public string Browse(string genre)
        {
           return "Hello from Store.Browse() ";
        }

        public string Details()
        {
            return "Hello from Store.Details()";
        }

    }
}

  不需要额外配置,浏览到/Store/Details就可以执行StoreController类中的Details方法,这就是操作中的路由.

  判断一个类是否是Controller的唯一方式,就是看该类是否继承自System.Web.Mvc.Controller. 

   Controoller 才是MVC中真正的核心, 每一个请求都必须通过控制器处理. 有些请求是不需要Model和View的. 

public string Browse(string genre)
        {
            string message = HttpUtility.HtmlEncode("Store.Browse, Genre= " + genre);
            return message;
        }

  利用HttpUtility.HtmlEncode来预处理用户输入. 这样就能阻止用户用链接向视图中注入JavaScript代码或HTML标记. 

  控制器可将查询字符串作为其操作方法的参数来接受. 

  ASP.NET MVC 的默认路由约定,就是将操作方法名称后面URL的这个片段作为一个参数, 该参数的名称为ID.  如果操作方法中有名为ID的参数, 那么ASP.NET MVC 会自动将这个URL片段作为参数传递过来. 

  

 

MVC中的Controller,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。