当前位置:首页>网络学院>程序开发>ASP.NET教程>文章内容

ASP.NET MVC Framework学习:控制器

[ 来源:http://www.it55.com | 作者: | 时间:2007-12-16 | 收藏 | 推荐 ] 【

 概述
  在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();
  }
  使用强类型传递ViewData
  通过前面的一些示例,已经看到了一些示例如何从控制器传递视图数据给View,在Controller中,传递视图数据到View,我们可以有两种方式选择,其中一种是使用强类型来传递视图数据,如下示例代码:
  
  [ControllerAction]
  public void Index()
  {
   BlogRepository repository = new BlogRepository();
  
   List<Post> posts = repository.GetAll();
   RenderView("Index", posts);
  }
  有朋友在回复中提到,如果想传递多个Model或者集合数据到View,该如何传递?这里需要再定义一个类型:
  
  public class HomeViewData
  {
   public List<Post> Posts
   {
   get; set;
   }
  
   public List<Category> Categories
   {
   get; set;
   }
  }
  然后在控制器中可以这样进行传递数据
  
  [ControllerAction]
  public void Index()
  {
   BlogRepository repository = new BlogRepository();
   List<Post> posts = repository.GetAll();
  
   List<Category> categories = repository.GetAllCategory();
  
   HomeViewData viewData = new HomeViewData();
   viewData.Posts = posts;
   viewData.Categories = categories;
  
   RenderView("Index", viewData);
  }
  使用强类型类来传递视图数据,有如下好处(来自于Scrottgu):
  
  1.避免使用字符串来查询对象,得到对你的控制器和视图代码的编译时检查
  
  2.避免需要在使用象C#这样的强类型语言中明确转换ViewData对象字典中的值
  
  3.在你的视图网页的标识文件以及后台代码文件中得到你的ViewData对象的自动代码intellisense
  
  4.可以使用代码重构工具来帮助自动化对整个应用和单元测试代码库的改动
  
  使用ViewData字典来传递数据
  在Controller基类中,有一个这样的字典定义:
  
  public IDictionary<string, object> ViewData { get; }
  这样我们可以直接把视图数据通过ViewData字段来传递,如下示例代码:
  
  [ControllerAction]
  public void Index()
  {
   BlogRepository repository = new BlogRepository();
   List<Post> posts = repository.GetAll();
  
   List<Category> categories = repository.GetAllCategory();
  
   ViewData["posts"] = posts;
   ViewData["categories"] = categories;
   RenderView("Index");
  }
  在试图中,可以这样来获取视图数据
  
  <div>
   <%foreach (Post post in (ViewData["posts"] as List<Post>))
   { %>
   <div class="postitem">

(编辑:IT资讯之家 www.it55.com

返回顶部
共2页: 上一页 1 [2] 下一页  

网友评论

[以下评论为网友观点,不代表本站。请自觉遵守互联网相关政策法规,所有连带责任均有评论者自负。]
[不超过250字]