不是自己想出來的,找了好久沒有找到相關的內容,根據源碼發現 返回視圖時時返回的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 }
從代碼可以看出 最后根據頁面上的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對象,然后構建這個視圖的 視圖上下文,利用傳的值 ViewData/TempData/ViewBag.~/Model 生成自己想要的靜態頁面,這樣的好處就是可以根據數據動態生成,而不用去做一整套XML或是正則的解析引擎。
