Welcome 微信登录

首页 / 网页编程 / ASP.NET / ASP.NET MVC Framework体验(4):控制器

ASP.NET MVC Framework体验(4):控制器2011-05-04TerryLee概述

在MVC中,Controller用来处理和回应用户的交互,选择使用哪个View来进行显 示,需要往视图中传递什么样的视图数据等。ASP.NET MVC Framework中提供了IController 接口和Controller基类两种类型,其中在Controller提供了一些MVC中常用的处理,如定位 正确的action并执行、为action方法参数赋值、处理执行过程中的错误、提供默认的 WebFormViewFactory呈现页面。IController只是提供了一个控制器的接口,如果用户想自 定义一个控制器的话,可以实现IController,它的定义如下:

public interface IController
{
void Execute(ControllerContext controllerContext);
}

定义控制器和action

在前面三篇的例子中,我们已 经定义过了控制器,只要继承于Controller就可以了:

public class BlogController : Controller
{
[ControllerAction]
public void Index()
{
BlogRepository repository = new BlogRepository();
List<Post> posts = repository.GetAll();
RenderView("Index", posts);
}
[ControllerAction]
public void New()
{
RenderView("New");
}
}
通过ControllerAction特性来指 定一个方法为action,ControllerAction的定义非常简单:

[AttributeUsage (AttributeTargets.Method)]
public sealed class ControllerActionAttribute : Attribute
{
public ControllerActionAttribute();
}