[上一篇]我们说道了ActionResult对象,作为控制器中动作执行结果对象,它负责把结果内容输出。ActionResult是个抽象类,存在一个方法:ExecuteResult,而在实际使用过程中,ActionResult会有各种子类来代表不同的返回结果;而我们最常用的就是ViewResult了。我们通过上篇可以看到最后呈现结果调用的是ActionResult.ExecuteResult方法,我们看下ViewResult对它的实现,在ViewResult的基类ViewResultBase中可以看到:
public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); if (string.IsNullOrEmpty(this.ViewName)) this.ViewName = context.RouteData.GetRequiredString("action"); ViewEngineResult viewEngineResult = (ViewEngineResult) null; if (this.View == null) { viewEngineResult = this.FindView(context); this.View = viewEngineResult.View; } TextWriter output = context.HttpContext.Response.Output; this.View.Render(new ViewContext(context, this.View, this.ViewData, this.TempData, output), output); if (viewEngineResult == null) return; viewEngineResult.ViewEngine.ReleaseView(context, this.View); }
主要的调用方法为FindView,在ActionResultBase中这个方法为抽象方法,它的实现在它的子类ViewResult,如下:
protected override ViewEngineResult FindView(ControllerContext context) { ViewEngineResult view = this.ViewEngineCollection.FindView(context, this.ViewName, this.MasterName); if (view.View != null) return view; StringBuilder stringBuilder = new StringBuilder(); foreach (string str in view.SearchedLocations) { stringBuilder.AppendLine(); stringBuilder.Append(str); } throw new InvalidOperationException(string.Format((IFormatProvider) CultureInfo.CurrentCulture, MvcResources.Common_ViewNotFound, new object[2] { (object) this.ViewName, (object) stringBuilder })); }
由代码可以看出,先是在视图引擎集合中根据控制器上下文和视图名称,模板名称返回返回一个ViewEngineResult对象,而结果是通过调用ViewEngineCollection的FindView获取的,通过查看ViewEngineCollection的方法FindView: