[英]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.