Implementation principles and procedures:
1. Through ViewEngines.Engines.FindView find the corresponding view, if it is a partial view, then use: ViewEngines.Engines.FindPartialView;
2. Set the model in the context object;
3. Call the render () method of the view to save the render result to a physical static file;
Using system;using system.io;using system.text;using system.web.mvc;namespace whir.foundation.ui{//<summary> Description: Static page Generation Help class///</summary> public class Staticpagehelper {//<summary>// /generate static pages from view view//</summary>//<param name= "Htmlpath" > The absolute path where static pages are stored </param> <param name= "Context" >ControllerContext</param>///<param Name= "ViewPath" > View name </param> ; <param name= "Mastername" > Template view name </param>//<param name= "model" > Parametric entity Model </param>/ <param name= "HTML" > Return information </param>//<param name= "ispartial" > whether to distribute Views </param>//&L T;returns> build succeeded returns true, failure false</returns> public static Ajaxresult generatestaticpage (String ViewPath, String Htmlpath, Controlle Rcontext context, object model = NULL, BOOL Ispartial = False, String mastername = "") {var ajaxresult = new Ajaxresult (); try {//Create a static page directory if (! Directory.Exists (Path.getdirectoryname (Htmlpath))) {Directory.CreateDirectory (path.getd Irectoryname (Htmlpath)); }//Delete existing static page if (File.exists (Htmlpath)) {file.delete (htm Lpath); } viewengineresult result = null; if (ispartial) {result = ViewEngines.Engines.FindPartialView (context, ViewPath); } else {result = ViewEngines.Engines.FindView (context, Viewpat h, Mastername); } if (model! = NULL) {Context. Controller.ViewData.Model = Model; }/* * Set temporary data dictionary as a static identity * You can use tempdata["IsStatic" on the view to control the display of certain elements. */if (!context. Controller.TempData.ContainsKey ("IsStatic")) {context. CONTROLLER.TEMPDATA.ADD ("IsStatic", true); } if (result. View! = null) {using (var sw = new StringWriter ()) { var viewcontext = new ViewContext (context, result. View, context. Controller.viewdata, context. Controller.tempdata, SW); Result. View.render (ViewContext, SW); string BODY = sw. ToString (); File.writealltext (Htmlpath, body, Encoding.UTF8); Ajaxresult.issucess = true; Ajaxresult.body = "Storage path:" + Htmlpath; }} else {ajaxresult.issucess = false; Ajaxresult.body = "Failed to generate static page!" No View found! "; }} catch (IOException ex) {ajaxresult.issucess = false; Ajaxresult.body = ex. Message; } catch (Exception ex) {ajaxresult.issucess = false; Ajaxresult.body = ex. Message; } return Ajaxresult; } }}
Ajaxresult is a class that encapsulates itself, and you can replace it with your own encapsulated class.
public class Ajaxresult
{
public bool Issucess {get; set;}
public string Body {get; set;}
}
ASP. NET MVC uses the Razor engine to generate static pages