最近在做一个生成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当模板的更多相关文章

  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. golang interface 转 string,int,float64

    func interface2String(inter interface{}) { switch inter.(type) { case string: fmt.Println("stri ...

  2. 应急响应-GHO提取注册表快照

    前言 备份文件.gho中找到机器的注册表 文件夹位置 在 C:\WINDOWS\SYSTEM32\CONFIG 下就是系统的注册表,一般情况下,这里面会有以下几个文件: default 默认注册表文件 ...

  3. win10 python27pyhton36共存

    先前安装了python36 然后安装python27,安装步骤如下 1. 到官网下载https://www.python.org/downloads/windows/,我的是win10 64位,选择了 ...

  4. 效率较高的php下读取文本文件的代码

    主要用下面这两个方法fread和 fgets的区别大家需要注意下     fread :以字节位计算长度,按照指定的长度和次数读取数据,遇到结尾或完成指定长度读取后停止.  fgets :整行读取,遇 ...

  5. telnetlib 中各种 read 函数的意义

    基本原理 要明白 telnetlib 中各个 read 函数的意义,首先要了解 telnetlib 的工作原理. telnetlib 首先通过 socket 连接从网络接收数据,把数据存储到自己的 r ...

  6. 027_磁盘维护命令du等

    一.du查看磁盘空间大小排除指定目录的的用法. 下面的例子为排除/data目录,因为/data目录是单独挂载的磁盘 [pe@jyall-3 /data]$ sudo du --exclude='/da ...

  7. C# AutoResetEvent 使用整理

    AutoResetEvent 允许线程通过发信号互相通信.通常,此通信涉及线程需要独占访问的资源. 线程通过调用 AutoResetEvent 上的 WaitOne 来等待信号.如果 AutoRese ...

  8. 基于Hadoop2.7.3集群数据仓库Hive1.2.2的部署及使用

    基于Hadoop2.7.3集群数据仓库Hive1.2.2的部署及使用 HBase是一种分布式.面向列的NoSQL数据库,基于HDFS存储,以表的形式存储数据,表由行和列组成,列划分到列族中.HBase ...

  9. Select2日常操作集合

    1.获得多选值 var arraySelected = $('#carTypes').select2("data"); var carTypesDesc = ''; for (va ...

  10. SQL Server 之 内部连接

    1.内部联接 2.外部联接 外部联接扩展了内部联接的功能,会把内联接中删除表源中的一些保留下来,由于保存下来的行不同,可将外部联接分为左联接和右联接. 2.1左联接: 如果左表的某一行在右表中没有匹配 ...