RazorEngine.Templating MVC中View当模板
最近在做一个生成JSON的功能,比较笨的办法就是把需要的数据拆分开,保存到数据库,在从数据库中取出来进行拼接。这种方法比较笨,代码就不贴了。
需要注意拼接的时的转义字符:
"\"smallChapter\"" + ":" +"\""
后来想用T4模板生成,但是有个把数据当参数传递的过程,没有克服。把没有克服的代码贴出来,有大神知道的话,可以帮忙解决。(host报错)
public class Testt4 { public class CustomTextTemplatingEngineHost : ITextTemplatingEngineHost, ITextTemplatingSessionHost { internal string TemplateFileValue; public string TemplateFile { get { return TemplateFileValue; } } private string fileExtensionValue = ".txt"; public string FileExtension { get { return fileExtensionValue; } } private Encoding fileEncodingValue = Encoding.UTF8; public Encoding FileEncoding { get { return fileEncodingValue; } } private CompilerErrorCollection errorsValue; public CompilerErrorCollection Errors { get { return errorsValue; } } public IList<string> StandardAssemblyReferences { get { return new string[] { typeof(System.Uri).Assembly.Location }; } } public IList<string> StandardImports { get { return new string[] { "System" }; } } public bool LoadIncludeText(string requestFileName, out string content, out string location) { content = System.String.Empty; location = System.String.Empty; if (File.Exists(requestFileName)) { content = File.ReadAllText(requestFileName); return true; } else { return false; } } public object GetHostOption(string optionName) { object returnObject; switch (optionName) { case "CacheAssemblies": returnObject = true; break; default: returnObject = null; break; } return returnObject; } public string ResolveAssemblyReference(string assemblyReference) { if (File.Exists(assemblyReference)) { return assemblyReference; } string candidate = Path.Combine(Path.GetDirectoryName(this.TemplateFile), assemblyReference); if (File.Exists(candidate)) { return candidate; } return ""; } public Type ResolveDirectiveProcessor(string processorName) { if (string.Compare(processorName, "XYZ", StringComparison.OrdinalIgnoreCase) == 0) { //return typeof(); } throw new Exception("Directive Processor not found"); } public string ResolvePath(string fileName) { if (fileName == null) { throw new ArgumentNullException("the file name cannot be null"); } if (File.Exists(fileName)) { return fileName; } string candidate = Path.Combine(Path.GetDirectoryName(this.TemplateFile), fileName); if (File.Exists(candidate)) { return candidate; } return fileName; } public string ResolveParameterValue(string directiveId, string processorName, string parameterName) { if (directiveId == null) { throw new ArgumentNullException("the directiveId cannot be null"); } if (processorName == null) { throw new ArgumentNullException("the processorName cannot be null"); } if (parameterName == null) { throw new ArgumentNullException("the parameterName cannot be null"); } return String.Empty; } public void SetFileExtension(string extension) { fileExtensionValue = extension; } public void SetOutputEncoding(System.Text.Encoding encoding, bool fromOutputDirective) { fileEncodingValue = encoding; } public void LogErrors(CompilerErrorCollection errors) { errorsValue = errors; } //public AppDomain ProvideTemplatingAppDomain(string content) //{ // return AppDomain.CreateDomain("Generation App Domain"); //} public ITextTemplatingSession CreateSession() { return Session; } public ITextTemplatingSession Session { get; set; } //https://blog.csdn.net/danielchan2518/article/details/51019083 public AppDomain ProvideTemplatingAppDomain(string content) { //Assembly myAssembly = Assembly.GetAssembly(this.GetType()); //string assemblePath = myAssembly.Location.Substring(0, myAssembly.Location.LastIndexOf("\\")); //AppDomainSetup ads = new AppDomainSetup() //{ // ApplicationName = "Generation App Domain", // ApplicationBase = assemblePath, // DisallowBindingRedirects = false, // DisallowCodeDownload = true, // ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile //}; //AppDomain domain = AppDomain.CreateDomain("Generation App Domain", null, ads); //return domain; return AppDomain.CurrentDomain; } } public static void TestT4() { CustomTextTemplatingEngineHost host = new CustomTextTemplatingEngineHost(); string filePath = @"E:\editsoft\t4.txt"; host.TemplateFileValue = filePath; string input = File.ReadAllText(filePath); // string input = @" //<#@template debug=""false"" hostspecific=""false"" language=""C#""#> //<#@ output extension="".txt"" encoding=""utf-8"" #> //<#@ parameter type=""Demo_T4.People"" name=""hzx"" #> //Name:<#= hzx.Name #> Age:<#= hzx.Age #> Sex:<#= hzx.Sex #> // "; host.Session = new TextTemplatingSession(); host.Session.Add("hzx", new People("韩兆新", 24, "男")); string output = new Engine().ProcessTemplate(input, host); Console.WriteLine(output); StringBuilder errorWarn = new StringBuilder(); foreach (CompilerError error in host.Errors) { errorWarn.Append(error.Line).Append(":").AppendLine(error.ErrorText); } Console.WriteLine( errorWarn.ToString()); } } [Serializable] public class People { public People(string name, uint age, string sex) { this.Name = name; this.Age = age; this.Sex = sex; } public string Name { set; get; } public uint Age { set; get; } public string Sex { set; get; } }
最后想到了MVC 的视图Rezor,当模板具体代码如下:
在控制器中写方法:通过写一个Ajax跳入这个方法
public ActionResult GetDataJson() { string url = Request.Url.ToString(); //获取参数 string bid = Request.QueryString[""]; string cid = Request.QueryString[""]; //获取数据定义成集合 ArrayList arry = GenerateJsonData(); ArrayList arrTitle = GetTile(); ArrayList arrlanmu = GetLanMuContent();
var config = new TemplateServiceConfiguration();
GetData(arry, arrTitle, arrlanmu, config);
}
GetData方法:
private void GetData(ArrayList arry, ArrayList arrTitle, ArrayList arrlanmu, TemplateServiceConfiguration config) { using (var service = RazorEngine.Templating.RazorEngineService.Create(config)) { var model = new { arrTitle, arry, arrlanmu }; //获取视图的路径 string templateFile = Server.MapPath("~/Views/ResolveTemplateJson/PhysicsJson.cshtml"); //打开文件的内容 string templateContent = System.IO.File.ReadAllText(templateFile, System.Text.Encoding.UTF8); //返回视图中的结果 string results = service.RunCompile(templateContent, string.Empty, null, model); //把结构中的特殊字符进行处理 results = results.Replace("<", "<").Replace(">", ">") .Replace("&", "&").Replace("'", "'").Replace(""", "\""); string filePath = GetFilePath(); GetWriteValue(results, filePath); //写入txt中 // string outputTextFile = @"d:\temp.txt"; // System.IO.File.WriteAllText(outputTextFile, results); } }
GetFilePath
private string GetFilePath() { string filePath = ""; if (Session["chapterNum"] != null) { int zhang = Convert.ToInt32(Session["chapterNum"]); int jie = Convert.ToInt32(Session["sectionNum"]); int xiaojie = Convert.ToInt32(Session["smallSectionNum"]); string jcName = Session["jcName"].ToString(); string xkName = Session["xkName"].ToString(); string NjName = Session["NjName"].ToString(); string gradeTerm = Session["gradeTerm"].ToString(); string webConfigFilePath = ConfigurationManager.AppSettings["FilePathConnectionString"].ToString(); filePath = string.Format(webConfigFilePath + "{0}{1}{2}{3}/{4:00}/{5:00}{6:00}/", NjName, xkName, jcName, gradeTerm, zhang, jie, xiaojie); } return filePath; }
GetWriteValue()
private void GetWriteValue(string results, string filePath) { string webMapFilePath = ConfigurationManager.AppSettings["FilePath"].ToString(); string Path = Server.MapPath(webMapFilePath + filePath); if (!Directory.Exists(Path)) { Directory.CreateDirectory(Path); } string FileName = "bookData"; if (!System.IO.File.Exists(Path + FileName + ".js")) { FileStream fsCreate = new FileStream(Path + FileName + ".js", FileMode.Create, FileAccess.Write);//创建写入文件 StreamWriter sw = new StreamWriter(fsCreate); sw.WriteLine(results);//开始写入值 sw.Close(); fsCreate.Close(); } else { FileStream fsCreate = new FileStream(Path + FileName + ".js", FileMode.Create, FileAccess.Write);//创建写入文件 StreamWriter sw = new StreamWriter(fsCreate); sw.WriteLine(results);//开始写入值 sw.Close(); fsCreate.Close(); } }
跳转视图的Ajax:
function ResolveTemplateJson() { var url = "/ResolveTemplateJson/GetDataJson/?csid=@ViewData[""]&bid=@ViewData[""]"; $.ajax({ url: url, type: "POST", success: function (data) { if (data == "ok") { alert("保存成功!!"); window.location.href = "/UEditor/Index/?csid=@ViewData[""]&bid=@ViewData[""]"; } else if (data == "error") { alert("保存失败"); } } }); }
视图的代码:
@for (int i = 0; i < Model.arrTitle.Count; i++) { if (Model.arrTitle[i].titles != null) { @:{ @:"smallChapter": "@Model.arrTitle[i].titles", @:"isActive":false, @://当前用户选择的小节 @:"ifstudy":false @:}, } } ], //全解版的内容 "content": [ //第一小节的内容 一小结有n个知识点 知识点里面包含小知识点 @for (int j = 0; j < Model.arrlanmu.Count; j++) { @:{ @:"id":"@Model.arrlanmu[j].id", @:"knowledge":"@Model.arrlanmu[j].knowledge", @:"process": @:"Introduction":"@Model.arrlanmu[j].Introduction", for (int m = 0; m < Model.arry.Count; m++) { if (@Model.arrlanmu[j].id == @Model.arry[m].id) { @:smallKnowledge:[{ @:"id":"@Model.arry[m].smallID", @:"fullVersion":[ @:"type":"textIntroduction", @:"smalltitle":"@Model.arry[m].smallTitle", @:"content":"@Model.arry[m].smallContent", @:}, @Model.arry[m].smallSubjectJson @:], @:} @:] } } @:} }
引入的命名空间:
using RazorEngine.Configuration; using RazorEngine.Templating;
Negut安装: