您的位置:首页 > 编程语言 > ASP

ASP.NET MVC学习笔记-----使用自定义的View Engine

2013-08-30 20:16 871 查看
我们都知道在ASP.NET MVC中自带了Razor View Engine,Razor十分的强大,可以满足我们绝大部分的需要。但是ASP.NET MVC的高度可扩展性,使我们可以使用自定义的View Engine,以满足我们自己的特殊需要。

首先,实现自定义的View Engine需要实现IViewEngine接口:

public interface IViewEngine
{
//使用指定的控制器上下文查找指定的分部视图。
ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache);
//使用指定的控制器上下文来查找指定的视图。
ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache);
//使用指定的控制器上下文来释放指定的视图。
void ReleaseView(ControllerContext controllerContext, IView view);
}


我们可以看出,View Engine的主要职责就是通过ControllerContext(包含HttpContext和当前Controller实例)和ViewName来查找指定视图,最终返回的是ViewEngineResult

,那么ViewEngineResult是什么呢?来看看ViewEngine的源码:

namespace System.Web.Mvc
{
public class ViewEngineResult
{
public ViewEngineResult(IEnumerable<string> searchedLocations)
{
if (searchedLocations == null)
{
throw new ArgumentNullException("searchedLocations");
}

SearchedLocations = searchedLocations;
}

public ViewEngineResult(IView view, IViewEngine viewEngine)
{
if (view == null)
{
throw new ArgumentNullException("view");
}
if (viewEngine == null)
{
throw new ArgumentNullException("viewEngine");
}

View = view;
ViewEngine = viewEngine;
}

public IEnumerable<string> SearchedLocations { get; private set; }
public IView View { get; private set; }
public IViewEngine ViewEngine { get; private set; }
}
}


ViewEngineResult有两个构造函数。如果你的View Engine针对一个请求能够提供view,那么就可以使用

public ViewEngineResult(IView view, IViewEngine viewEngine)


如果你的View Engine不能提供view,那么可以使用

public ViewEngineResult(IEnumerable<string> searchedLocations)


参数searchedLocations表示寻找view的命名空间集合。

在实现自定义的View Engine后,要如何才能MVC使用它呢,我们需要将View Engine添加到ViewEngines.Engines集合中:

public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
ViewEngines.Engines.Insert(0, new DebugDataViewEngine());

WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}


因为MVC可以注册多个View Engine并且是按索引顺序使用View Engine来处理请求,如果我们想让自定义的View Enginge优先处理请求,那么就需要将它放在索引0的位置。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: