返璞归真 asp.net mvc (7) - asp.net mvc 3.0 新特性之 Controller
作者:介绍asp.net mvc 之 asp.net mvc 3.0 新特性之 Controller:
- Global Action Filter
- 可以在标记为 ChildActionOnly 的 Action 上使用 OutputCache
- ViewBag
- 新增了一些 Action Result
示例1、Global Action Filter 的 DemoGlobal.asax.cs(注册全局的 Action Filter)
protected void Application_Start(){ AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); /* * 演示 Global Action Filter */ // 实例化一个 Filter var handleError = new HandleErrorAttribute(); // 指定 HandleErrorAttribute 的 View handleError.View = "Error2"; // Order 属性的默认值为:-1,即不会被应用,所以这里要修改一下 handleError.Order = 0; // 将 Filter 对象添加到全局 Filters 集合中 GlobalFilters.Filters.Add(handleError);}
Web.config
ControllerDemoController.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace MVC30.Controllers{ public class ControllerDemoController : Controller { // 用于演示 Global Action Filter public ActionResult GlobalActionFilter() { throw new Exception("exception"); } }}
GlobalActionFilter.cshtml(访问此页会抛出异常,然后跳转到Error2)
@{ ViewBag.Title = "Global Action Filter";}GlobalActionFilter
Error2.cshtml(自定义错误页)
@{ Layout = null;}Error Sorry, an error occurred while processing your request
Sorry, an error occurred while processing your request
Sorry, an error occurred while processing your request
Sorry, an error occurred while processing your request
Sorry, an error occurred while processing your request
2、标记为 ChildActionOnly 的 Action 支持 OutputCacheControllerDemoController.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace MVC30.Controllers{ public class ControllerDemoController : Controller { public ActionResult ChildActionOnlyDemo() { return View(); } // ChildActionOnly - 指定 Action 只能让 RenderAction 调用 // OutputCache() - 缓存。Duration - 缓存秒数。VaryByParam - none, *, 多个参数用逗号隔开。也可以通过配置文件对缓存做设置 [ChildActionOnly] [OutputCache(Duration = 5)] public PartialViewResult _GetCurrentTime() { var currentTime = DateTime.Now; return PartialView(currentTime); } }}
_GetCurrentTime.cshtml
@* 通过 @model 指定 Model 的类型,同时 Model 对象就是 Action 返回的数据*@@model DateTimecurrentTime: @Model.ToString("yyyy-MM-dd HH:mm:ss")
ChildActionOnlyDemo.cshtml
@{ ViewBag.Title = "可以在标记为 ChildActionOnly 的 Action 上使用 OutputCache";}ChildActionOnlyDemo
@{ Html.RenderAction("_GetCurrentTime"); }@Html.Action("_GetCurrentTime")
3、 新增了 ViewBagControllerDemoController.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace MVC30.Controllers{ public class ControllerDemoController : Controller { // 用于 ViewBagDemo public ActionResult ViewBagDemo() { // ViewBag 的本质就是把 ViewData 包装成为 dynamic 类型 ViewBag.Message = "ViewBag 的 Demo"; return View(); } }}
ViewBagDemo.cshtml
@{ ViewBag.Title = "ViewBag";}ViewBag
Message: @ViewBag.Message
4、 新增的 Action Result
Controller 中新增了一些 Action Result: HttpNotFoundResult, HttpRedirectResult, HttpStatusCodeResult
OK