今天体验了一下NVelocity对数据的几种绑定。代码如下
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Collections.Generic;
using Commons.Collections;
using NVelocity;
using NVelocity.App;
using NVelocity.Context;
using NVelocity.Runtime;
using System.Data;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//创建VelocityEngine实例对象
VelocityEngine velocity = new VelocityEngine();
//使用设置初始化VelocityEngine
ExtendedProperties props = new ExtendedProperties();
props.AddProperty(RuntimeConstants.INPUT_ENCODING, "gb2312");
props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "gb2312");
props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Server.MapPath(@""));
velocity.Init(props);
//从文件中读取模板
Template template = velocity.GetTemplate("for.vm");
//为模板变量赋值
IContext context = new VelocityContext();
context.Put("from", "危超云");
context.Put("to", "someone");
context.Put("subject", "Welcome to NVelocity");
context.Put("name", "John Doe");
//这个是模板类赋值
//user ok = new user();
//ok.Name = "xxx";
//ok.Id = 222;
//context.Put("ok", ok);
//这个是泛型数据
//IList<user> users = new List<user>();
//user user1=new user(11,"wei9931");
//users.Add(user1);
//user user2 = new user(22, "baidu.com");
//users.Add(user2);
//context.Put("arrayList", users);
//这个是Tabel赋值
DataTable myDataTable=new DataTable();
myDataTable.Columns.Add("CustomerID");
myDataTable.Columns.Add("CompanyName");
myDataTable.Columns.Add("ContactName");
myDataTable.Columns.Add("Address");
DataRow myNewDataRow = myDataTable.NewRow();
myNewDataRow["CustomerID"] = 11;
myNewDataRow["CompanyName"] = "T1 Company";
myNewDataRow["ContactName"] = "Jason Price";
myNewDataRow["Address"] = "1 Main Street";
myDataTable.Rows.Add(myNewDataRow);
DataRow myNewDataRow1 = myDataTable.NewRow();
myNewDataRow1["CustomerID"] = 22;
myNewDataRow1["CompanyName"] = "T2 Company";
myNewDataRow1["ContactName"] = "Jason Price";
myNewDataRow1["Address"] = "1 Main Street";
myDataTable.Rows.Add(myNewDataRow1);
IList<user> users = new List<user>();
for (int i = 0; i < myDataTable.Rows.Count; i++)
{
user user1 = new user(Convert.ToInt32(myDataTable.Rows[i]["CustomerID"].ToString()), myDataTable.Rows[i]["CompanyName"].ToString());
users.Add(user1);
}
context.Put("myDataTable", users);
//这个是数组复值
//IList arrayList = new ArrayList();
//arrayList.Add("上海");
//arrayList.Add("杭州");
//arrayList.Add("大连");
//context.Put("arrayList", arrayList);
//合并模板
StringWriter writer = new StringWriter();
template.Merge(context, writer);
//输出
Response.Write(writer.ToString().Replace("\r\n", ""));
}
}