软件下载 | 资讯教程 | 最近更新 | 下载排行 | 一键转帖 | 发布投稿
您的位置:最火下载站 > 网络编程 > ASP.NET > ASP.NET MVC 1.0 流程分析 (ViewResult)

ASP.NET MVC 1.0 流程分析 (ViewResult)

Controller.View() 的作用是 "显示" 一个特定的 "模板结果页",这也是多数 Action 的执行结果。

public abstract class Controller : ControllerBase,
IActionFilter, IAuthorizationFilter, IDisposable, IExceptionFilter, IResultFilter
{
protected internal virtual ViewResult View(string viewName, string masterName, object model)
{
if (model != null)
{
ViewData.Model = model;
}

return new ViewResult
{
ViewName = viewName,
MasterName = masterName,
ViewData = ViewData,
TempData = TempData
};
}
}

ViewResult.ExecuteResult 会被 ControllerActionInvoker.InvokeAction() 所调用,以完成最终的页面显示(Render)。

public abstract class ViewResultBase : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
...

ViewEngineResult result = null;

if (View == null)
{
result = FindView(context);
View = result.View;
}

ViewContext viewContext = new ViewContext(context, View, ViewData, TempData);
View.Render(viewContext, context.HttpContext.Response.Output);

...
}

protected abstract ViewEngineResult FindView(ControllerContext context);

public ViewEngineCollection ViewEngineCollection
{
get { return _viewEngineCollection ?? ViewEngines.Engines; }
set { _viewEngineCollection = value; }
}
}

public class ViewResult : ViewResultBase
{
protected override ViewEngineResult FindView(ControllerContext context)
{
ViewEngineResult result = ViewEngineCollection.FindView(context, ViewName, MasterName);
if (result.View != null)
{
return result;
}

...
}
}

很显然,ViewEngines.Engines 起着关键的作用。从名称来看,它存储了多个视图显示引擎供 FindView() 选择。

public static class ViewEngines
{
private readonly static ViewEngineCollection _engines = new ViewEngineCollection
{
new WebFormViewEngine()
};

public static ViewEngineCollection Engines
{
get { return _engines; }
}
}

public class ViewEngineCollection : Collection<IViewEngine>
{
public virtual ViewEngineResult FindView(ControllerContext controllerContext,
string viewName, string masterName)
{
...

Func<IViewEngine, ViewEngineResult> cacheLocator =
e => e.FindView(controllerContext, viewName, masterName, true);

Func<IViewEngine, ViewEngineResult> locator =
e => e.FindView(controllerContext, viewName, masterName, false);

return Find(cacheLocator, locator);
}

private ViewEngineResult Find(Func<IViewEngine, ViewEngineResult> cacheLocator,
Func<IViewEngine, ViewEngineResult> locator)
{
ViewEngineResult result;

...

List<string> searched = new List<string>();

foreach (IViewEngine engine in Items)
{
if (engine != null)
{
result = locator(engine);

if (result.View != null)
{
return result;
}

searched.AddRange(result.SearchedLocations);
}
}

return new ViewEngineResult(searched);
}
}

相关阅读
网友评论
栏目导航
推荐软件