ASP. NET MVC uses Razor engine to generate static pages

  • 2021-09-20 19:53:03
  • OfStack

Recently, I am studying ASP. NET MVC to generate static pages, so today is also a study note!

Implementation principle and steps:

1. Find the corresponding view through ViewEngines. Engines. FindView. If it is a partial view, use ViewEngines. Engines. FindPartialView;

2. Set Model in the context object;

3. Call the Render () method of the view and save the rendering 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> 
    ///    According to View View generates static pages  
    /// </summary> 
    /// <param name="htmlPath"> 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 solid model </param> 
    /// <param name="html"> Return information </param> 
    /// <param name="isPartial"> Whether to distribute views </param> 
    /// <returns> Successful generation returns true, Failure false</returns> 
    public static AjaxResult GenerateStaticPage(string viewPath, 
                          string htmlPath, 
                          ControllerContext context, object model = null, bool isPartial = false, 
                          string masterName = "") 
    { 
      var ajaxResult = new AjaxResult(); 
      try 
      { 
        // Create a directory for storing static pages                
        if (!Directory.Exists(Path.GetDirectoryName(htmlPath))) 
        { 
          Directory.CreateDirectory(Path.GetDirectoryName(htmlPath)); 
        } 
        // Delete an existing static page  
        if (File.Exists(htmlPath)) 
        { 
          File.Delete(htmlPath); 
        } 
        ViewEngineResult result = null; 
        if (isPartial) 
        { 
          result = ViewEngines.Engines.FindPartialView(context, viewPath); 
        } 
        else 
        { 
          result = ViewEngines.Engines.FindView(context, viewPath, masterName); 
        } 
 
        if (model != null) 
        { 
          context.Controller.ViewData.Model = model; 
        } 
 
        /* 
         *  Set the temporary data dictionary as a static identity  
         *  You can use the TempData["IsStatic"] 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! View not 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 self-encapsulated class, and you can replace it with a self-encapsulated class.


  public class AjaxResult
  {
    public bool IsSucess { get; set; }
    public string Body { get; set; }
  }

Related articles: