1. 自己拼表格造成的问题
自己拼表格,html代码和服务器端C#代码嵌在一起,不利于美工修改
2. 模板引擎(会一种就可以)
有很多种,Nvelocity,Razor等,编写模板—提供数据—渲染html标签
在模板中,可以获取变量,属性,方法;可以写对象,进行判断循环等
在模板html中写C#代码时,要加@符号,而要在模板html中表示@,要使用@@
3. 在使用Razor模板时,要注意使用的版本
dll是对应.net framework版本的
vs2013对应framework4.5 vs2010对应framework4.0
4. 三层项目(模板引擎使用案例)--MyPhotos
注意:当类库项目修改完成后,一定要重新生成(重新生成dll)
通过Razor.Compile可以把html编译成缓存中的存储的部分,用name标识
public static void Compile(string url, string name)
{
string path = HttpContext.Current.Request.MapPath("Views/"+url);
string html = File.ReadAllText(path);
Razor.Compile(html, name);
}
通过Razor.Parse可以把模板内容编写成html内容,在其模板html中可以使用
@Include“缓存名字”的方法,将几个部分拼接成一个html内容
public static void Render(string url, object o)
{
string path = HttpContext.Current.Request.MapPath("Views/" + url);
string html = File.ReadAllText(path);
html = Razor.Parse(html, o);
HttpContext.Current.Response.Write(html);
}
5. 把数据传到Include缓存之中,修改缓存内容
1)一般处理程序中使用匿名类型
List<Photos> list = photosBLL.GetAllPhotos();
List<Photos> top = photosBLL.GetTopPhotos(6);
var data = new { List = list, Top = top };
2)在模板html中
<ul>
@for(int i=0; i<@Model.List.Count; i++){
<li>
<div class="name">@Model.List[i].PTitle</div>
<div class="screen"><a href="details.ashx?id=@Model.List[i].PId "><img src="images/@Model.List[i].PUrl" width = "200" height = "200" alt=""></a></div>
</li>
}
</ul>
3)在一般处理程序中调用Compile方法,要使用data.GetType()这个参数
Razor.Compile(html1, data.GetType(), "header");
public static void Compile(string url,Type type,string name)
{
//添加引用 system.web.dll
string path = HttpContext.Current.Request.MapPath("~/views/" + url);
string html = File.ReadAllText(path);
Razor.Compile(html,type, name);
}