zoukankan      html  css  js  c++  java
  • MVC 根据模板动态生成静态页面

    不是自己想出来的,找了好久没有找到相关的内容,根据源码发现 返回视图时时返回的ActionResult 类型的对象,然后执行ExecuteResult 方法,源码如下:

     1 public override void ExecuteResult(ControllerContext context)
     2 {
     3     if (context == null)
     4     {
     5         throw new ArgumentNullException("context");
     6     }
     7     if (string.IsNullOrEmpty(this.ViewName))
     8     {
     9         this.ViewName = context.RouteData.GetRequiredString("action");
    10     }
    11     ViewEngineResult result = null;
    12     if (this.View == null)
    13     {
    14         result = this.FindView(context);
    15         this.View = result.View;
    16     }
    17     TextWriter output = context.HttpContext.Response.Output;
    18     ViewContext viewContext = new ViewContext(context, this.View, this.ViewData, this.TempData, output);
    19     this.View.Render(viewContext, output);
    20     if (result != null)
    21     {
    22         result.ViewEngine.ReleaseView(context, this.View);
    23     }
    24 }
    ExecuteResult

    从代码可以看出 最后根据页面上的model数据,构建了视图上下文,用来渲染成HTML代码,生成的内容在TextWrite流中

    所以这种模式,自己可以自己创建一个类似的:

     1 string html = string.Empty;
     2             IView view = ViewEngines.Engines.FindView(context, tempFilePath, string.Empty).View;
     3 
     4             using (System.IO.StringWriter sw = new System.IO.StringWriter())
     5             {
     6                 ViewContext vc = new ViewContext(context, view, dic, tempDic, sw);
     7                 vc.View.Render(vc, sw);
     8                 html = sw.ToString();
     9             }
    10             return html;
    View Code

    找到自己自定义的模板页面,得到一个View对象,然后构建这个视图的 视图上下文,利用传的值 ViewData/TempData/ViewBag.~/Model 生成自己想要的静态页面,这样的好处就是可以根据数据动态生成,而不用去做一整套XML或是正则的解析引擎。

  • 相关阅读:
    ls 按大小排序 按时间排序
    【u035】奶牛的电信
    【record】#10
    【record】10.30..11.6
    【33.33%】【codeforces 608C】Chain Reaction
    【44.19%】【codeforces 608D】Zuma
    【22.73%】【codeforces 606D】Lazy Student
    【27.40%】【codeforces 599D】Spongebob and Squares
    【26.67%】【codeforces 596C】Wilbur and Points
    【13.91%】【codeforces 593D】Happy Tree Party
  • 原文地址:https://www.cnblogs.com/JsonYang/p/4517764.html
Copyright © 2011-2022 走看看