首页 > 代码库 > Asp.net动态页面静态化之输出对象属性(实体关联)
Asp.net动态页面静态化之输出对象属性(实体关联)
Asp.net动态页面静态化之输出对象属性(实体关联)
模板引擎不单单能够输出单一的数据,还能直接输出对象的属性
using System; using System.Collections.Generic; using System.Linq; using System.Web; using NVelocity.Runtime; using NVelocity; using NVelocity.App; namespace czbk { /// <summary> /// Handler2 的摘要说明 /// </summary> public class Handler2 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html";//plain表示普通文本格式输出 静态化应该输出html格式文本 User user = new User(); user.Username = "王大锤"; user.Userphone = "18312345678"; Role role = new Role(); role.Roleid = "1001"; role.Rolename = "超级搞笑王"; user.User_Role1 = role;//给关联对象赋值 VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/"));//模板文件所在的目录 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); vltContext.Put("u", user);//设置參数。在模板中能够通过$u来引用 Template vltTemplate = vltEngine.GetTemplate("Users.htm"); System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } public bool IsReusable { get { return false; } } } public class User { private string username; public string Username { get { return username; } set { username = value; } } private string userphone; public string Userphone { get { return userphone; } set { userphone = value; } } private Role User_Role;//引入一个关联的类对象 public Role User_Role1 { get { return User_Role; } set { User_Role = value; } } } public class Role { private string roleid; public string Roleid { get { return roleid; } set { roleid = value; } } private string rolename; public string Rolename { get { return rolename; } set { rolename = value; } } } }
前台代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <form action='Handler2.ashx'> 用户名:<input type="text" name='username' value=http://www.mamicode.com/'$u.username' />
>
Asp.net动态页面静态化之输出对象属性(实体关联)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。