簡體   English   中英

保存動態生成的HTML頁面ASP.NET

[英]Save dynamically generated HTML page ASP.NET

使用ASP.NET MVC,我生成了一個html頁面

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

更改最后一位數字將更改我使用@HTML helpers導入的字段的值

我想將此頁面自動保存到服務器的某個位置,以使其靜態。

諸如PersonNr15.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>

您需要做的是將視圖呈現為一個字符串,然后像對待其他任何字符串一樣將其保存到文件中。 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);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM