保存动态生成的HTML页面ASP.NET

本文关键字:页面 ASP NET HTML 动态 保存 | 更新日期: 2023-09-27 18:26:50

使用ASP.NET MVC,我生成了一个html页面

示例:http://example1234.com/Persons/details/15

更改最后一个数字将更改我使用@HTML助手导入的字段的值

我想自动将此页面保存到服务器的某个位置,使其成为静态页面。

类似于PersonNr15.html,生成的内容硬编码到该页面中。

      @model MvcApplication3.Models.Person
      @{
      ViewBag.Title = "Details";
      }
      <h2>Details</h2>
     <fieldset>
     <legend>Person</legend>
        <p>@Html.DisplayFor(model => model.FirstName)</p>
        <p>@Html.DisplayFor(model => model.LastName)</p>
      </fieldset>

保存动态生成的HTML页面ASP.NET

您需要做的是将视图呈现为字符串,然后像保存其他字符串一样将该字符串保存到文件中。MVC视图到字符串的呈现包含在前面回答的问题中,例如This question

我自己更改了代码。我使用了自制的模板,并更改了#NAME等单词#更改文件中的可变单词后,保存文件,用它制作PDF。然后完成。(PDF不是问题的一部分,但我为感兴趣的人添加了它)。

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Person person)
        datadir = ConfigurationManager.AppSettings["datadir"];
        //datadirectory defined in Web.config
        //also possible to hardcode it here, example: "c:/windows/PDFfolder"
        wkhtmltopdf = ConfigurationManager.AppSettings["wkhtmltopdf"];
        //directory to the file "wkhtmltopdf", downloaded it somewhere
        //just like above, defined at web.config possible to hardcode it in
        ViewData["IsModelValid"] = ModelState.IsValid ? "true" : "false";
        //valid checker

        if (ModelState.IsValid)      //check if valid
        {                
        db.People.Add(person);       //add to db
            db.SaveChanges();
        var fileContents1 = System.IO.File.ReadAllText(datadir + "Template.html"); 
        //get template from datadirectory
        fileContents1 = fileContents1.Replace("#NAME#", person.Name);
        //replace '#NAME#' by the name from the database table person.Name
       System.IO.File.WriteAllText(datadir + "tmp''Template." + person.ID + ".html", fileContents1);
       //create a new html page with the replaced text
       //name of the file equals the ID of the person

            var pdf1 = new ProcessStartInfo(wkhtmltopdf); //start process wkhtmltopdf
            pdf1.CreateNoWindow = true;  //don't create a window
            pdf1.UseShellExecute = false; //don't use a shell
            pdf1.WorkingDirectory = datadir + "tmp''"; //where to create the pdf
            pdf1.Arguments = "-q -n --disable-smart-shrinking Overeenkomst." + person.ID + ".html Overeenkomst." + person.ID + ".pdf";
          //get the html to convert and make a pdf with the same name in the same directory
        }
        return View(person);
    }