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安装:
RazorEngine.Templating MVC中View当模板的更多相关文章
- ASP.NET MVC 中 View 的设计
1. 前言 感觉有好长时间没有接触View 了,周末闲来无事,翻翻书桌上的书来回顾回顾ASP.NET MVC中View的相关内容. 2. View概述 View 通过应用程序在Action 中返回 ...
- mvc中view与controll之间传递参数时,可以使用url进行传递
mvc中view与controller之间传递参数时,可以使用url进行传递,但是在url的地址中需要加上“id=123”这样的东西才行. 具体如代码: window.location.href = ...
- Asp.Net MVC中使用ACE模板之Jqgrid
第一次看到ACE模板,有种感动,有种相见恨晚的感觉,于是迅速来研究.它本身是基于bootstrap和jqueryui,但更nice,整合之后为后台开发节省了大量时间. 发现虽然不是完美,整体效果还是不 ...
- Asp.net mvc 中View 的呈现(二)
[toc] 上一节介绍了 Asp.net mvc 中除 ViewResult 外的所有的 ActionResult,这一节介绍 ViewResult. ViewResultBase ViewResul ...
- 关于MVC中View使用自定义方法
今天学习到了在MVC的View中使用自定义方法,很简单,下面分享一下. 1.首先在项目下面建立一个文件夹,用于存我们写的自定义方法. 2.在新建文件夹中新增一个类,命名随便取(最好还是和自定义方法关联 ...
- MVC中在RAZOR 模板里突然了现了 CANNOT RESOLVE SYMBOL ‘VIEWBAG’ 的错误提示
然后在Razor中出现了@ViewBag的不可用,@Url不可用,@Html 这些变量都不能用了. 异常提示: 编译器错误消息: CS0426: 类型“XX.Model.System”中不存在类型名称 ...
- MVC中使用T4模板
参考博文 http://www.cnblogs.com/heyuquan/archive/2012/07/26/2610959.html 图片释义 1.简单示例,对基本的模块标记 2.根据上图生成的类 ...
- MVC中view和controller相互传值的方法
MVC项目中,在view层如果使用前台框架,框架中会有封装好的相互传值方法.但是,那些postdata[][]方法不一定能够满足功能需求,反而一些常用的传值方法可能会刚好解决它们的不足.总结如下: 一 ...
- Asp.net mvc 中View的呈现(一)
[toc] 我们知道针对客户端的请求,最终都会转换为对 Controller 中的一个 Action 方法的调用,指定的 Action 方法会返回一个 ActionResult 类型的实例来响应该请求 ...
随机推荐
- C/C++中 # 的神奇作用:把宏参数字符串化/贴合宏参数
一.一般用法 我们使用#把宏参数变为一个字符串,用##把两个宏参数贴合在一起. #define STR(s) #s #define CONS(a,b) int(a##e##b) printf(ST ...
- C 和 C++ 一些基础
位运算: Part1: #include <iostream> using namespace std; int main(int argc, char *argv[]) { //unsi ...
- python3-深浅copy
转载:https://www.cnblogs.com/ctztake/p/8194275.html 术语 变量:是一个系统表的元素,拥有指向对象的连接空间. 对象:被分配的一块内存,存储其所代表的值. ...
- 在windows下用vagrant建立lnmp开发环境
1.安装vagrant,vitrualbox 2.下载homestead的box包,并添加到vagrant 下载地址: https://atlas.hashicorp.com/laravel/boxe ...
- Flash硬件原理
1.2.1. 什么是Flash Flash全名叫做Flash Memory,从名字就能看出,是种数据存储设备,存储设备有很多类,Flash属于非易失性存储设备(Non-volatile Memory ...
- hibernate框架学习之二级缓存
缓存的意义 l应用程序中使用的数据均保存在永久性存储介质之上,当应用程序需要使用数据时,从永久介质上进行获取.缓存是介于应用程序与永久性存储介质之间的一块数据存储区域.利用缓存,应用程序可以将使用的数 ...
- 简单的三级联动demo
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...
- sysstat-----获取服务器负载历史记录
sysstat工具与负载历史回放 很多系统负载过高的时候我们是无法立即获知或者立即解决的,当检测到或者知道历史的高负载状况时,可能需要回放历史监控数据,这时 sar 命令就派上用场了,sar命令同样来 ...
- python-迭代器、生成器、内置函数及面向过程编程
一.迭代器 迭代器是迭代取值的工具,迭代是一个重复的过程,每一次重复都是基于上一次的结果而来的. 为什么要用迭代器呢? 1.可以不依赖索引取值 2.同一时刻在内存中只有一个值,不会过多的占用内存 如何 ...
- 从外部设置传入Go变量
前提:必须在build/run时指定 -ldflags="-X main.a=2.0 -X main.b=1" , 且a,b必须是string的变量,不能是常量, 不能是struc ...