Asp.net Vnext 实现IView
概述
Iview定义很简单,就是根据View上下文和TextWriter对象实现对View的呈现。
实现
实现IViewEngine
public class TestViewEngine : IViewEngine { public ViewEngineResult FindPartialView(ActionContext context, string partialViewName) { //如果viewName等于partial-test-view 就采用 TestPartialView if (string.Equals(partialViewName, "partial-test-view", StringComparison.Ordinal)) { return ViewEngineResult.Found(partialViewName, new TestPartialView()); } return ViewEngineResult.NotFound(partialViewName, new[] { partialViewName }); } public ViewEngineResult FindView(ActionContext context, string viewName) { //如果viewName等于test-view 就采用 TestView if (string.Equals(viewName, "test-view")) { return ViewEngineResult.Found(viewName, new TestView()); } return ViewEngineResult.NotFound(viewName, new[] { viewName }); } }
实现IView
public class TestPartialView : IView { public string Path { get; set; } public async Task RenderAsync(ViewContext context) { //这里没有视图,就把 world 输出浏览器 await context.Writer.WriteLineAsync("world"); } }
public class TestView : IView { public string Path { get; set; } public async Task RenderAsync(ViewContext context) { await context.Writer.WriteLineAsync("<img src='"+context.ViewBag.Images + "' />"); } }
控制器
public class HomeController: Controller { public ViewResult Index() { return View(); } public ViewResult TestView() { ViewBag.Images = "/images/ASP-NET-Banners-01.png"; return View("test-view"); } }
启动类
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc() .ConfigureMvc(options => { //加入视图引擎 options.ViewEngines.Insert(0, typeof(TestViewEngine)); }); } public void Configure(IApplicationBuilder app) { app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } }
运行
表达有限这里有一篇介绍的文章:http://www.cnblogs.com/artech/archive/2012/08/22/view-engine-01.html