日期:2014-05-16  浏览次数:20830 次

Asp.Net MVC4 系列--进阶篇之View

自定义一个ViewEngine

一般的,不需要自定义创建一个View Engine,但为了说明View部分的全貌,先从自定义ViewEngine开始,逐渐全面了解MVCFramework的View部分实现。

 

需要实现的接口

public interface IViewEngine {
ViewEngineResult  FindPartialView(ControllerContextcontrollerContext,
string partialViewName, bool useCache);
ViewEngineResult  FindView(ControllerContext controllerContext,
string viewName, string masterName, bool useCache);
void ReleaseView(ControllerContext controllerContext, IViewview);
}


接口说明:

1.      查找PartialView

2.      查找View

3.      释放View

 

除了最后一个函数返回值为空外,前两个函数都需要返回一个ViewEngineResult ,代码如下:

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 newArgumentNullException("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的构造可以通过两种构造函数:

1.      如果找不到View,那么给一个已经找了哪些路径(最后会show给user,如果找了所有的路径,到最后都没有找到)

2.      如果找到了,那么给这个view对象和它的ViewEngine(由谁来render)

 

 

IView接口:

public interface IView {
void  Render(ViewContext  viewContext, TextWriter  writer);
}


一个函数:一手拿着ViewContext(包含了这次请求的信息),一手拿着writer,把信息写成html,render到客户端,推送到浏览器直接消费。

 

示例实现:

1.      Controller

  public class TestController : Controller
{

        public ActionResult Index()
        {
            ViewData["Key1"] ="Value1";
            ViewData["Key2"] =DateTime.Now;
            ViewData["Key3"] = 3;
            return View("Test");
        }
}


 

实现了TestController,里面有一个Index Action,返回了一个Test View(在Viewsfolder中不存在)。

2.      Customize View

 

public class ViewDataPrinter : IView
    {
       public void Render(ViewContext viewContext, TextWriter writer)
       {
           Write(writer, "---View Data---");
           foreach (string key in viewContext.ViewData.Keys)
           {
                Write(writer, "Key: {0},Value: {1}", key,
                viewContext.ViewData[key]);
           }
       }
       private void  Write(TextWriter writer, string  template, params object[] values)
       {
           writer.Write(string.Format(template, values) + "<p/>");
       }
}


功能:把viewContext中的ViewData打印出来

&nb