MVC中的Controller

时间:2023-12-16 12:08:50

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

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

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

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

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace MvcMusicStore.Controllers
{
public class HomeController : Controller
{ public ActionResult Index()
{
        // 将默认内容修改为"I like cake!" 后即可直接显示在主页上.
ViewBag.Message = "I like cake!";
return View();
} public ActionResult About()
{
ViewBag.Message = "Your app description page."; return View();
} public ActionResult Contact()
{
ViewBag.Message = "Your contact page."; return View();
}
}
}

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片段作为参数传递过来.