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='$u.username' /><br /> 用户电话:<input type="text" name='userphone' value="$u.userphone" /><br /> 用户角色名:<input type="text" name='userrolename' value="$u.User_Role1.rolename" /><br /> 用户角色名2:<input type="text" name='userrolename' value="$u.User_Role1.Rolename" /><br /> <span style="color:red;">可能是html不区分大小写 所以这时调用大小写都是可以的 欢迎大家指出错误</span> </form> </body> </html>
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-13 21:58:54