最近在做一个生成JSON的功能,比较笨的办法就是把需要的数据拆分开,保存到数据库,在从数据库中取出来进行拼接。这种方法比较笨,代码就不贴了。

需要注意拼接的时的转义字符:

  1. "\"smallChapter\"" + ":" +"\""

  后来想用T4模板生成,但是有个把数据当参数传递的过程,没有克服。把没有克服的代码贴出来,有大神知道的话,可以帮忙解决。(host报错)

  1. public class Testt4
  2. {
  3. public class CustomTextTemplatingEngineHost : ITextTemplatingEngineHost, ITextTemplatingSessionHost
  4. {
  5.  
  6. internal string TemplateFileValue;
  7. public string TemplateFile
  8. {
  9. get { return TemplateFileValue; }
  10. }
  11.  
  12. private string fileExtensionValue = ".txt";
  13. public string FileExtension
  14. {
  15. get { return fileExtensionValue; }
  16. }
  17.  
  18. private Encoding fileEncodingValue = Encoding.UTF8;
  19. public Encoding FileEncoding
  20. {
  21. get { return fileEncodingValue; }
  22. }
  23. private CompilerErrorCollection errorsValue;
  24. public CompilerErrorCollection Errors
  25. {
  26. get { return errorsValue; }
  27. }
  28. public IList<string> StandardAssemblyReferences
  29. {
  30. get
  31. {
  32. return new string[]
  33. {
  34. typeof(System.Uri).Assembly.Location
  35. };
  36. }
  37. }
  38. public IList<string> StandardImports
  39. {
  40. get
  41. {
  42. return new string[]
  43. {
  44. "System"
  45. };
  46. }
  47. }
  48.  
  49. public bool LoadIncludeText(string requestFileName, out string content, out string location)
  50. {
  51. content = System.String.Empty;
  52. location = System.String.Empty;
  53.  
  54. if (File.Exists(requestFileName))
  55. {
  56. content = File.ReadAllText(requestFileName);
  57. return true;
  58. }
  59. else
  60. {
  61. return false;
  62. }
  63. }
  64.  
  65. public object GetHostOption(string optionName)
  66. {
  67. object returnObject;
  68. switch (optionName)
  69. {
  70. case "CacheAssemblies":
  71. returnObject = true;
  72. break;
  73. default:
  74. returnObject = null;
  75. break;
  76. }
  77. return returnObject;
  78. }
  79.  
  80. public string ResolveAssemblyReference(string assemblyReference)
  81. {
  82. if (File.Exists(assemblyReference))
  83. {
  84. return assemblyReference;
  85. }
  86.  
  87. string candidate = Path.Combine(Path.GetDirectoryName(this.TemplateFile), assemblyReference);
  88. if (File.Exists(candidate))
  89. {
  90. return candidate;
  91. }
  92. return "";
  93. }
  94.  
  95. public Type ResolveDirectiveProcessor(string processorName)
  96. {
  97. if (string.Compare(processorName, "XYZ", StringComparison.OrdinalIgnoreCase) == 0)
  98. {
  99. //return typeof();
  100. }
  101. throw new Exception("Directive Processor not found");
  102. }
  103.  
  104. public string ResolvePath(string fileName)
  105. {
  106. if (fileName == null)
  107. {
  108. throw new ArgumentNullException("the file name cannot be null");
  109. }
  110. if (File.Exists(fileName))
  111. {
  112. return fileName;
  113. }
  114. string candidate = Path.Combine(Path.GetDirectoryName(this.TemplateFile), fileName);
  115. if (File.Exists(candidate))
  116. {
  117. return candidate;
  118. }
  119. return fileName;
  120. }
  121.  
  122. public string ResolveParameterValue(string directiveId, string processorName, string parameterName)
  123. {
  124. if (directiveId == null)
  125. {
  126. throw new ArgumentNullException("the directiveId cannot be null");
  127. }
  128. if (processorName == null)
  129. {
  130. throw new ArgumentNullException("the processorName cannot be null");
  131. }
  132. if (parameterName == null)
  133. {
  134. throw new ArgumentNullException("the parameterName cannot be null");
  135. }
  136. return String.Empty;
  137. }
  138.  
  139. public void SetFileExtension(string extension)
  140. {
  141. fileExtensionValue = extension;
  142. }
  143.  
  144. public void SetOutputEncoding(System.Text.Encoding encoding, bool fromOutputDirective)
  145. {
  146. fileEncodingValue = encoding;
  147. }
  148.  
  149. public void LogErrors(CompilerErrorCollection errors)
  150. {
  151. errorsValue = errors;
  152. }
  153.  
  154. //public AppDomain ProvideTemplatingAppDomain(string content)
  155. //{
  156. // return AppDomain.CreateDomain("Generation App Domain");
  157. //}
  158.  
  159. public ITextTemplatingSession CreateSession()
  160. {
  161. return Session;
  162. }
  163.  
  164. public ITextTemplatingSession Session
  165. {
  166. get;
  167. set;
  168. }
  169.  
  170. //https://blog.csdn.net/danielchan2518/article/details/51019083
  171.  
  172. public AppDomain ProvideTemplatingAppDomain(string content)
  173. {
  174. //Assembly myAssembly = Assembly.GetAssembly(this.GetType());
  175. //string assemblePath = myAssembly.Location.Substring(0, myAssembly.Location.LastIndexOf("\\"));
  176. //AppDomainSetup ads = new AppDomainSetup()
  177. //{
  178. // ApplicationName = "Generation App Domain",
  179. // ApplicationBase = assemblePath,
  180. // DisallowBindingRedirects = false,
  181. // DisallowCodeDownload = true,
  182. // ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
  183. //};
  184. //AppDomain domain = AppDomain.CreateDomain("Generation App Domain", null, ads);
  185. //return domain;
  186. return AppDomain.CurrentDomain;
  187. }
  188.  
  189. }
  190.  
  191. public static void TestT4()
  192. {
  193. CustomTextTemplatingEngineHost host = new CustomTextTemplatingEngineHost();
  194. string filePath = @"E:\editsoft\t4.txt";
  195. host.TemplateFileValue = filePath;
  196. string input = File.ReadAllText(filePath);
  197.  
  198. // string input = @"
  199. //<#@template debug=""false"" hostspecific=""false"" language=""C#""#>
  200. //<#@ output extension="".txt"" encoding=""utf-8"" #>
  201. //<#@ parameter type=""Demo_T4.People"" name=""hzx"" #>
  202. //Name:<#= hzx.Name #> Age:<#= hzx.Age #> Sex:<#= hzx.Sex #>
  203. // ";
  204.  
  205. host.Session = new TextTemplatingSession();
  206. host.Session.Add("hzx", new People("韩兆新", 24, "男"));
  207.  
  208. string output = new Engine().ProcessTemplate(input, host);
  209. Console.WriteLine(output);
  210.  
  211. StringBuilder errorWarn = new StringBuilder();
  212. foreach (CompilerError error in host.Errors)
  213. {
  214. errorWarn.Append(error.Line).Append(":").AppendLine(error.ErrorText);
  215. }
  216. Console.WriteLine( errorWarn.ToString());
  217.  
  218. }
  219. }
  220.  
  221. [Serializable]
  222. public class People
  223. {
  224. public People(string name, uint age, string sex)
  225. {
  226. this.Name = name;
  227. this.Age = age;
  228. this.Sex = sex;
  229. }
  230. public string Name
  231. { set; get; }
  232. public uint Age
  233. { set; get; }
  234. public string Sex
  235. { set; get; }
  236. }

  最后想到了MVC 的视图Rezor,当模板具体代码如下:

在控制器中写方法:通过写一个Ajax跳入这个方法

  1. public ActionResult GetDataJson()

  2. string url = Request.Url.ToString(); //获取参数
  3. string bid = Request.QueryString[""];
  4. string cid = Request.QueryString[""];
  5. //获取数据定义成集合
  6. ArrayList arry = GenerateJsonData();
  7. ArrayList arrTitle = GetTile();
  8. ArrayList arrlanmu = GetLanMuContent();

var config = new TemplateServiceConfiguration();
                      GetData(arry, arrTitle, arrlanmu, config);

  GetData方法:

  1. private void GetData(ArrayList arry, ArrayList arrTitle, ArrayList arrlanmu, TemplateServiceConfiguration config)
  2. {
  3. using (var service = RazorEngine.Templating.RazorEngineService.Create(config))
  4. {
  5. var model = new { arrTitle, arry, arrlanmu };
  6.  
  7. //获取视图的路径
  8. string templateFile = Server.MapPath("~/Views/ResolveTemplateJson/PhysicsJson.cshtml");
  9. //打开文件的内容
  10. string templateContent = System.IO.File.ReadAllText(templateFile, System.Text.Encoding.UTF8);
  11. //返回视图中的结果
  12. string results = service.RunCompile(templateContent, string.Empty, null, model);
  13. //把结构中的特殊字符进行处理
  14. results = results.Replace("<", "<").Replace(">", ">")
  15. .Replace("&", "&").Replace("'", "'").Replace(""", "\"");
  16.  
  17. string filePath = GetFilePath();
  18.  
  19. GetWriteValue(results, filePath);
  20.  
  21. //写入txt中
  22. // string outputTextFile = @"d:\temp.txt";
  23. // System.IO.File.WriteAllText(outputTextFile, results);
  24. }
  25. }
  1. GetFilePath
  1. private string GetFilePath()
  2. {
  3. string filePath = "";
  4. if (Session["chapterNum"] != null)
  5. {
  6. int zhang = Convert.ToInt32(Session["chapterNum"]);
  7. int jie = Convert.ToInt32(Session["sectionNum"]);
  8. int xiaojie = Convert.ToInt32(Session["smallSectionNum"]);
  9. string jcName = Session["jcName"].ToString();
  10. string xkName = Session["xkName"].ToString();
  11. string NjName = Session["NjName"].ToString();
  12. string gradeTerm = Session["gradeTerm"].ToString();
  13. string webConfigFilePath = ConfigurationManager.AppSettings["FilePathConnectionString"].ToString();
  14. filePath = string.Format(webConfigFilePath + "{0}{1}{2}{3}/{4:00}/{5:00}{6:00}/",
  15. NjName, xkName, jcName, gradeTerm, zhang, jie, xiaojie);
  16. }
  17.  
  18. return filePath;
  19. }
  1. GetWriteValue()
  1. private void GetWriteValue(string results, string filePath)
  2. {
  3. string webMapFilePath = ConfigurationManager.AppSettings["FilePath"].ToString();
  4. string Path = Server.MapPath(webMapFilePath + filePath);
  5. if (!Directory.Exists(Path))
  6. {
  7. Directory.CreateDirectory(Path);
  8. }
  9. string FileName = "bookData";
  10.  
  11. if (!System.IO.File.Exists(Path + FileName + ".js"))
  12. {
  13. FileStream fsCreate = new FileStream(Path + FileName + ".js", FileMode.Create, FileAccess.Write);//创建写入文件
  14. StreamWriter sw = new StreamWriter(fsCreate);
  15. sw.WriteLine(results);//开始写入值
  16. sw.Close();
  17. fsCreate.Close();
  18. }
  19. else
  20. {
  21. FileStream fsCreate = new FileStream(Path + FileName + ".js", FileMode.Create, FileAccess.Write);//创建写入文件
  22. StreamWriter sw = new StreamWriter(fsCreate);
  23. sw.WriteLine(results);//开始写入值
  24. sw.Close();
  25. fsCreate.Close();
  26. }
  27. }

  跳转视图的Ajax:

  1. function ResolveTemplateJson() {
  2. var url = "/ResolveTemplateJson/GetDataJson/?csid=@ViewData[""]&bid=@ViewData[""]";
  3. $.ajax({
  4. url: url,
  5. type: "POST",
  6. success: function (data) {
  7. if (data == "ok") {
  8. alert("保存成功!!");
  9. window.location.href = "/UEditor/Index/?csid=@ViewData[""]&bid=@ViewData[""]";
  10. } else if (data == "error") {
  11. alert("保存失败");
  12. }
  13. }
  14. });
  15. }

  视图的代码:

  1. @for (int i = 0; i < Model.arrTitle.Count; i++)
  2. {
  3. if (Model.arrTitle[i].titles != null)
  4. {
  5. @:{
  6. @:"smallChapter": "@Model.arrTitle[i].titles",
  7. @:"isActive":false,
  8. @://当前用户选择的小节
  9. @:"ifstudy":false
  10. @:},
  11. }
  12. }
  13. ],
  14. //全解版的内容
  15. "content": [
  16. //第一小节的内容 一小结有n个知识点 知识点里面包含小知识点
  17. @for (int j = 0; j < Model.arrlanmu.Count; j++)
  18. {
  19. @:{
  20. @:"id":"@Model.arrlanmu[j].id",
  21. @:"knowledge":"@Model.arrlanmu[j].knowledge",
  22. @:"process":
  23. @:"Introduction":"@Model.arrlanmu[j].Introduction",
  24. for (int m = 0; m < Model.arry.Count; m++)
  25. {
  26. if (@Model.arrlanmu[j].id == @Model.arry[m].id)
  27. {
  28. @:smallKnowledge:[{
  29. @:"id":"@Model.arry[m].smallID",
  30. @:"fullVersion":[
  31. @:"type":"textIntroduction",
  32. @:"smalltitle":"@Model.arry[m].smallTitle",
  33. @:"content":"@Model.arry[m].smallContent",
  34. @:},
  35. @Model.arry[m].smallSubjectJson
  36. @:],
  37. @:}
  38. @:]
  39. }
  40. }
  41.  
  42. @:}
  43. }

  

  引入的命名空间:

  1. using RazorEngine.Configuration;
  2. using RazorEngine.Templating;

  Negut安装:

RazorEngine.Templating MVC中View当模板的更多相关文章

  1. ASP.NET MVC 中 View 的设计

    1. 前言  感觉有好长时间没有接触View 了,周末闲来无事,翻翻书桌上的书来回顾回顾ASP.NET MVC中View的相关内容. 2. View概述  View 通过应用程序在Action 中返回 ...

  2. mvc中view与controll之间传递参数时,可以使用url进行传递

    mvc中view与controller之间传递参数时,可以使用url进行传递,但是在url的地址中需要加上“id=123”这样的东西才行. 具体如代码: window.location.href = ...

  3. Asp.Net MVC中使用ACE模板之Jqgrid

    第一次看到ACE模板,有种感动,有种相见恨晚的感觉,于是迅速来研究.它本身是基于bootstrap和jqueryui,但更nice,整合之后为后台开发节省了大量时间. 发现虽然不是完美,整体效果还是不 ...

  4. Asp.net mvc 中View 的呈现(二)

    [toc] 上一节介绍了 Asp.net mvc 中除 ViewResult 外的所有的 ActionResult,这一节介绍 ViewResult. ViewResultBase ViewResul ...

  5. 关于MVC中View使用自定义方法

    今天学习到了在MVC的View中使用自定义方法,很简单,下面分享一下. 1.首先在项目下面建立一个文件夹,用于存我们写的自定义方法. 2.在新建文件夹中新增一个类,命名随便取(最好还是和自定义方法关联 ...

  6. MVC中在RAZOR 模板里突然了现了 CANNOT RESOLVE SYMBOL ‘VIEWBAG’ 的错误提示

    然后在Razor中出现了@ViewBag的不可用,@Url不可用,@Html 这些变量都不能用了. 异常提示: 编译器错误消息: CS0426: 类型“XX.Model.System”中不存在类型名称 ...

  7. MVC中使用T4模板

    参考博文 http://www.cnblogs.com/heyuquan/archive/2012/07/26/2610959.html 图片释义 1.简单示例,对基本的模块标记 2.根据上图生成的类 ...

  8. MVC中view和controller相互传值的方法

    MVC项目中,在view层如果使用前台框架,框架中会有封装好的相互传值方法.但是,那些postdata[][]方法不一定能够满足功能需求,反而一些常用的传值方法可能会刚好解决它们的不足.总结如下: 一 ...

  9. Asp.net mvc 中View的呈现(一)

    [toc] 我们知道针对客户端的请求,最终都会转换为对 Controller 中的一个 Action 方法的调用,指定的 Action 方法会返回一个 ActionResult 类型的实例来响应该请求 ...

随机推荐

  1. C/C++中 # 的神奇作用:把宏参数字符串化/贴合宏参数

    一.一般用法   我们使用#把宏参数变为一个字符串,用##把两个宏参数贴合在一起. #define STR(s) #s #define CONS(a,b) int(a##e##b) printf(ST ...

  2. C 和 C++ 一些基础

    位运算: Part1: #include <iostream> using namespace std; int main(int argc, char *argv[]) { //unsi ...

  3. python3-深浅copy

    转载:https://www.cnblogs.com/ctztake/p/8194275.html 术语 变量:是一个系统表的元素,拥有指向对象的连接空间. 对象:被分配的一块内存,存储其所代表的值. ...

  4. 在windows下用vagrant建立lnmp开发环境

    1.安装vagrant,vitrualbox 2.下载homestead的box包,并添加到vagrant 下载地址: https://atlas.hashicorp.com/laravel/boxe ...

  5. Flash硬件原理

    1.2.1. 什么是Flash Flash全名叫做Flash Memory,从名字就能看出,是种数据存储设备,存储设备有很多类,Flash属于非易失性存储设备(Non-volatile Memory ...

  6. hibernate框架学习之二级缓存

    缓存的意义 l应用程序中使用的数据均保存在永久性存储介质之上,当应用程序需要使用数据时,从永久介质上进行获取.缓存是介于应用程序与永久性存储介质之间的一块数据存储区域.利用缓存,应用程序可以将使用的数 ...

  7. 简单的三级联动demo

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...

  8. sysstat-----获取服务器负载历史记录

    sysstat工具与负载历史回放 很多系统负载过高的时候我们是无法立即获知或者立即解决的,当检测到或者知道历史的高负载状况时,可能需要回放历史监控数据,这时 sar 命令就派上用场了,sar命令同样来 ...

  9. python-迭代器、生成器、内置函数及面向过程编程

    一.迭代器 迭代器是迭代取值的工具,迭代是一个重复的过程,每一次重复都是基于上一次的结果而来的. 为什么要用迭代器呢? 1.可以不依赖索引取值 2.同一时刻在内存中只有一个值,不会过多的占用内存 如何 ...

  10. 从外部设置传入Go变量

    前提:必须在build/run时指定 -ldflags="-X main.a=2.0 -X main.b=1" , 且a,b必须是string的变量,不能是常量, 不能是struc ...