原帖地址:http://www.cnblogs.com/QLeelulu/archive/2008/10/04/1303672.html

Controller是MVC中比較重要的一部分。差点儿全部的业务逻辑都是在这里进行处理的,而且从Model中取出数据。

在ASP.NET MVC Preview5中。将原来的Controller类一分为二,分为了Controller类和ControllerBase类。

Controller类继承自ControllerBase类,而ControllerBase实现是了IController接口。

ControllerBase实现了IController接口的Execute方法,在Route匹配到Controller之后。就会调用Execute方法来进入Controller的处理。

这里还定义了一个抽象的方法ExecuteCore方法,该方法会在Execute方法的最后被调用。ControllerBase还定义了三个核心的属性。我们在后面会具体讨论TempData和ViewData。

Controller类除了继承自ControllerBase类以外。还实现了好几个Filter接口。Filter我们在后面再具体讨论。

public abstract class Controller
: ControllerBase, IActionFilter, IAuthorizationFilter, IDisposable, IExceptionFilter, IResultFilter{ }

Controller类还定义非常多实用的方法,我们新建的Controller都必须继承自这个Controller类。比如我们新建一个AdminController:

public class AdminController : Controller
{
}

Action方法

以下谈一下在Controller中比較重要的Action方法。在ASP.NET MVC中URL都是映射到Controller中的某个Action中,然后由匹配的Action来处理我们的业务逻辑并返回view的。

Controller中的public的方法都被当作是Action方法。Action方法通常返回一个ActionResult的结果。比如我们为前面的AdminController定义一个Setting的Action方法。用于设置Blog的一些基本參数:


public class AdminController : Controller
{
    public ActionResult Setting()
    {
        throw new NotImplementedException();
    }
}

默认情况下,Action方法的方法名就是这个Action的Action名(Action名指的是Route中匹配Action方法的URL的那部分。

比如url:Home/Index。当中Index就是Action名)。

这里为什么要提到这个Action名呢?应为Action名是能够定义的。使用ActionNameAttribute来定义。

请看以下的演示样例:


public ActionResult Setting()
{
    throw new NotImplementedException();
} [ActionName("Setting")]
public ActionResult SaveSetting()
{
    throw new NotImplementedException();
}

这两个Action方法的Action名都为"Setting",即对于url:Admin/Setting ,能同一时候匹配到这两个Action方法。假设一个URL同一时候匹配到两个Action方法的话。程序会抛出一个错误:

假设我们希望这两个Action的Action名都为Setting。Setting()就用于显示一个表单页面给用户,而SaveSetting()就用于保存用户提交过来的表单数据,我们该怎么做呢?我们能够利用AcceptVerbsAttribute来设置,这个Attribute用来定义Action方法会匹配指定的HttpMethod。比如以下的代码:


[AcceptVerbs("GET")]
public ActionResult Setting()
{
    throw new NotImplementedException();
} [ActionName("Setting"), AcceptVerbs("POST")]
public ActionResult SaveSetting()
{
    throw new NotImplementedException();
}

这样,对于HttpMethod为"GET"的client请求,就会匹配到Setting()来显示一个表单给用户。假设用户POST回来的表单数据,则会匹配到SaveSetting()上面去。我们就能够处理用户POST过来的数据并保存到数据库。

在这里AcceptVerbsAttribute是继承自ActionSelectionAttribute的。我们也能够继承自ActionSelectionAttribute来自己定义自己想要实现的功能。这个我们后面会具体解说。假设你比較心急,能够看下Asp.net Mvc Preview 5 体验--实现ActionSelectionAttribute来推断是否为AJAX请求而选择不同的Action这篇文章。

假设你想将一个public的方法设置为不是Action方法,那么你就要为该public的方法加入NonAction的Attribute:

Action方法的參数

比如我们要在AdminController中定义一个编辑日志的Action方法:

public ActionResult EditPost(int? id)
{
    throw new NotImplementedException();
}

对于URL:Admin/EditPost/2 。上面的參数会自己主动被赋值为2。ASP.NET MVC在匹配Route的时候会依据Route的设置自己主动为Action方法的參数赋值。

所曾经面的id參数会被自己主动赋值为2的前提是,在Route配置的时候,必须指定了id參数。比如:

routes.MapRoute(
    "Default",                                             
// Route 的名称
    "{controller}/{action}/{id}",                          
// 带有參数的URL
    new { controller
= "Home", action
= "Index", id
= "" } 
// 设置默认的參数
);

假设我们将Route改动为:

routes.MapRoute(
    "Default",                                             
// Route 的名称
    "{controller}/{action}/{para}",                          
// 带有參数的URL
    new { controller
= "Home", action
= "Index",
para = "" } 
// 设置默认的參数
);

则前面的Action方法的參数必须改动为public ActionResult EditPost(int?
para){ },使Action方法的參数和Route中定义的參数名同样,ASP.NET MVC才干自己主动为Action方法的參数赋值。

ActionResult

Action方法返回ActionResult类型的结果。ASP.NET MVC为我们提供了几种ActionResult的实现。例如以下:

  • ViewResult. 呈现视图页给client。

    由View 方法返回.

  • RedirectToRouteResult. 重定向到另外一个Route。由RedirectToAction 和RedirectToRoute 方法返回.

  • RedirectResult. 重定向到另外一个URL。


    Redirect 方法返回.

  • ContentResult. 返回普通的内容。比如一段字符串。


    Content 方法返回.

  • JsonResult. 返回JSON结果。由
    Json 方法返回.

  • EmptyResult. 假设Action必须返回空值,能够返回这个结果。Controller中没有实现的方法。能够return new EmptyResult();.

当然我们也能够自定一个我们的ActionResult返回给client,比如一个RssResult。

能够參考Asp.Net MVC实践 - 自己定义ActionResult实现Rss输出 (基于ASP.NET MVC Preview 3)这篇文章。

通常情况下。我们的Controller可能有一些同样的情况,比如我们在各个Controller中都有可能会在出错或者什么时候想要显示一条提示信息给用户,或者有一些共同的数据要呈现的。这时候,我们最好就定义一个我们自己的Controller的基类:


public class BaseController : Controller
{
    public BaseController()
    {     }     protected ActionResult ShowMsg(List<string>
msgs)
    {
        throw new NotImplementedException();
    }     public ActionResult Message()
    {
        throw new NotImplementedException();
    }
}

然后。其它的Controller都继承自这个BaseController :


public class AdminController : BaseController
{
    [AcceptVerbs("GET")]
    public ActionResult Setting()
    {
        throw new NotImplementedException();
    }     [ActionName("Setting"), AcceptVerbs("POST")]
    public ActionResult SaveSetting()
    {
        throw new NotImplementedException();
    }     public ActionResult EditPost(int? id)
    {
        throw new NotImplementedException();
    }
}

ASP.NET MVC 入门4、Controller与Action的更多相关文章

  1. ASP.NET mvc下在Controller下action的跳转方式

    在ASP.NET mvc下,action有多种挑战方式: return RedirectToAction("Index");//一个参数时在本Controller下 如果Redir ...

  2. Asp.Net MVC<六>:Controller、Action 待续

    控制器 抽象类Controller Visual Studio的向导创建的Controller类型继承自抽象类Controller. 它是ControllerBase的子类. 实现了IControll ...

  3. ASP.NET MVC 入门8、ModelState与数据验证

    原帖地址:http://www.cnblogs.com/QLeelulu/archive/2008/10/08/1305962.html ViewData有一个ModelState的属性,这是一个类型 ...

  4. ASP.NET MVC 入门系列教程

    ASP.NET MVC 入门系列教程 博客园ASP.NET MVC 技术专题 http://kb.cnblogs.com/zt/mvc/ 一个居于ASP.NET MVC Beta的系列入门文章,有朋友 ...

  5. [转]ASP.NET MVC 入门8、ModelState与数据验证

    ViewData有一个ModelState的属性,这是一个类型为ModelStateDictionary的ModelState类型的字典集合.在进行数据验证的时候这个属性是比较有用的.在使用Html. ...

  6. ASP.NET MVC 入门

    ASP.NET MVC 入门 (Learning ASP.NET MVC) 传统的WebForm发展到如今出现不少的缺陷, 比如为了解决Http的无状态WebForm模式使用了ViewsState来保 ...

  7. 26、ASP.NET MVC入门到精通——后台管理区域及分离、Js压缩、css、jquery扩展

    本系列目录:ASP.NET MVC4入门到精通系列目录汇总 有好一段时间没更新博文了,最近在忙两件事:1.看书,学习中...2.为公司年会节目做准备,由于许久没有练习双截棍了,难免生疏,所以现在临时抱 ...

  8. Asp.net MVC入门视频教程

    编程开发 > Asp.net视频教程 > Asp.net MVC入门视频教程 > 1.传统web处理方式和mvc处理方式 上传日期:2014-08-16 10:02:45  相关摘要 ...

  9. ASP.NET MVC 3.0 Controller基础

    ASP.NET MVC 3.0 Controller基础   1.Controller类与方法 Controller(控制器)是ASP.NET MVC的核心,负责处理浏览器请求,并作出响应.Cotro ...

随机推荐

  1. Conservative GC (Part one)

    目录 保守式GC 不明确的根 指针和非指针的区别 貌似指针的非指针 不明确数据结构 优点 准确式GC 正确的根 打标签 不把寄存器和栈等当做根 优点 缺点 间接引用 经由句柄引用对象 优缺点 保守式G ...

  2. 喜马拉雅FM

    import requestsimport jsonstart_url ='https://www.ximalaya.com/revision/play/album?albumId=3595841&a ...

  3. 一个Web报表项目的性能分析和优化实践(五):重构有助于性能优化么?

    项目从初次开发到现在,已经快3年了.期间,有N个工程师参与过. 需求方面:增加减少,反反复复,无数次:人力方面:增加减少,不稳定:时间方面:功能开发着急上线,Bug开发紧急修复. 因此,代码臃肿,问题 ...

  4. 【Codeforces Round #459 (Div. 2) A】Eleven

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 这个数列增长很快的. 直接暴力模拟看看是不是它的一项就好了 [代码] #include <bits/stdc++.h> ...

  5. CSUOJ 1603 Scheduling the final examination

    1603: Scheduling the final examination Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 49  Solved: 1 ...

  6. OpenStack_Swift源代码分析——Object-auditor源代码分析(2)

    1 Object-aduitor审计详细分析 上一篇文章中,解说了Object-aduitor的启动,当中审计的详细运行是AuditorWorker实现的.在run_audit中实例化了Auditor ...

  7. iOS项目开发实战——学会使用TableView列表控件(二)

    要在iOS开发中使用TableView列表控件,不仅能够直接使用TableViewController作为整个主界面,并且还能够使用TableView控件来实现.使用TableView能够进行很多其它 ...

  8. 给Linux添加新用户,新建用户,新建帐号

    给Linux添加新用户,新建用户,新建帐号 添加用户组 sudo groupadd groupname 添加用户 sudo useradd username -m -s /sbin/nologin - ...

  9. 怎么成为合格的WEB前端开发工程师

    web前端开发工程师目前来讲是一个热门职位,但是要成为一个合格的web前端开发工程师,需要掌握的知识可不少,零度就简单的为大家讲讲. 大致的来讲,web前端开发工程师需要掌握的知识有:HTML.CSS ...

  10. 网站平台的favicon.ico的logo

        <link rel="shortcut icon" href="http://www.uuop.com/icotemp/2017061703035984/f ...