不拖控件ASP.NET――NVelocity(2)
來源:程序員人生 發布時間:2015-01-28 08:58:52 閱讀次數:3542次
上節課我們講述了NVelocity的簡單利用,但是沒有和數據庫打交道,這次我們來和數據庫連接實現人員的增刪改查。
1. 上篇博客回顧
鏈接:http://blog.csdn.net/u010955843/article/details/42528761
開講之前,我們先來回顧上1節課講的內容,主要是兩個頁面,1個是1般處理程序的頁面,另外一個是渲染后的模板。
? 機制
上篇博客中我們建立1個person類,并且在1般處理程序中對其進行了賦值,以后交給了模板(html)進行數據填充,渲染成html頁,以后生成的純html文本返回給1般處理程序將,1般處理程序將其返回給閱讀器進行解析,并且顯示。
? 好處
實現了數據和邏輯和界面的分離:數據給了模板(1般由html擔當),最后1般處理程序拿到渲染html進行輸出;模板不管數據來源,只是知道表格中需要設置幾行幾列;1般處理程序只是取數據,傳給模板,不管模板會把數據渲染成甚么模樣的,也就是各自只是負責自己的那1塊就能夠了
2. 與數據庫連接實現人員增刪改查
上節課我們只是在1般處理程序中寫的數據源對象,那末在傳統web開發NVelocity如何數據庫進行交互的呢,我們先來介紹程序編寫的步驟。
? 建立數據庫并且建表
可以自己定,我們的庫為CRUDTest,表明為Persons

設置Id為自增的,我們可以手動輸入幾條記錄
? CommonHelper
和上次1樣,我們首先下載NVelocity的DLL,以后將其添加到建立的相應項目下,直接拖進項目下面便可,以后添加對它的援用便可。
上次我們是將模板寫在1個1般處理程序中,但是我們知道這樣的只是適用1個或少數的處理程序,要是想要到達模板的復用或方便的使用,我們可以將其進行封裝,放到1個類中便可,這樣實現了方法的復用。
我們知道這里只是有兩個參數不1樣,行將渲染的模板,另外一個是將要填充模板的文件或數據。
具體代碼以下:
<strong><span style="font-family:Microsoft YaHei;font-size:14px;">using NVelocity;
using NVelocity.App;
using NVelocity.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//using NVelocity;using NVelocity.App;using NVelocity.Runtime;必須引入的
//這個類用于封裝Nvelocity模板的渲染
namespace yinqingmuban
{
public class commonHelper
{
/// <summary>
/// 用data數據填充templateName模板,渲染生成html返回
/// </summary>
/// <param name="templateName">模板名字</param>
/// <param name="data">填充模板數據</param>
/// <returns></returns>
public static string RenderHtml(string templateName, object data)
{
VelocityEngine vltEngine = new VelocityEngine();
vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夾,我們遵從上次講的我們還是放在templates這個文件夾中,自己也能夠新建別的名字的
vltEngine.Init(); //引擎初始化
VelocityContext vltContext = new VelocityContext();
vltContext.Put("Data", data);//設置參數,在模板中可以通過$data來援用
Template vltTemplate = vltEngine.GetTemplate(templateName);//渲染的html模板
System.IO.StringWriter vltWriter = new System.IO.StringWriter();
vltTemplate.Merge(vltContext, vltWriter);
string html = vltWriter.GetStringBuilder().ToString();
return html;
}
}
}</span></strong>
? Sqlhelper
相信大家都學過3層,這里不再做過量的介紹。封裝了1系列的增刪改查的方法,并且建立了數據庫的里連接。這里不再展現了
? 配置文件
用于配置連接數據庫的字符串,這樣便于我們靈活更換數據庫,而不用于更改代碼內部。
<strong><span style="font-family:Microsoft YaHei;font-size:14px;"><connectionStrings>
<add name="conStr" connectionString="data source=.;database=CRUDTest;uid=sa;pwd=123456;"/>
</connectionStrings></span></strong>
? 人員顯示的1般處理程序(personlist.ashx)
這里主要是讀取數據,然后把它渲染到html頁上進行輸出。
<strong><span style="font-family:Microsoft YaHei;font-size:14px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
namespace yinqingmuban
{
/// <summary>
/// personlist 的摘要說明
/// </summary>
public class personlist : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
//context.Response.Write("Hello World");
DataTable dt = sqlHelper.ExecuteDataTable("select * from Persons");
//DataTable不是集合,所以沒法foreach遍歷,DataTable的Rows屬性
//代表表格中的數據行的集合(DataRow的集合),1般傳遞DataRowCollection
//給模板方便遍歷
string html = commonHelper.RenderHtml("personlist.html", dt.Rows);
context.Response.Write(html);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}</span></strong>
? 建立人員列表的渲染模板(personlist.html)
<strong><span style="font-family:Microsoft YaHei;font-size:14px;"><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf⑻"/>
<title></title>
</head>
<body>
<!-- 人員的操作處理,增刪改查 -->
<a href="personEdit.ashx?Action=AddNew">新增人員</a>
<!--//變量data中的每行,并且輸入每行中的每列的字段值-->
<table>
<thead>
<tr><td>刪除</td><td>編輯</td><td>姓名</td><td>年齡</td><td>郵箱</td></tr>
</thead>
<tbody>
#foreach($person in $Data)
<tr><td><a href="personEdit.ashx?Action=Delete&Id=$person.Id">刪除</a></td><td><a href="personEdit.ashx?Action=Edit&Id=$person.Id">編輯</a></td><td>$person.Name</td><td>$person.Age</td><td>$person.Email</td></tr>
#end
</tbody>
</table>
</body>
</html>
</span></strong>
? 對列表進行增刪改(personEdit.ashx)
<strong><span style="font-family:Microsoft YaHei;font-size:14px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
namespace yinqingmuban
{
/// <summary>
/// personEdit 的摘要說明
/// </summary>
public class personEdit : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
//PersonEdit.ashx?action=AddNew
//PersonEdit.ashx?action=Edit&Id=3
string action = context.Request["action"];
if (action == "AddNew")
{
//判斷是不是含有Save并且等于true,如果是的話就說明是點擊【保存】按鈕要求來的
bool save = Convert.ToBoolean(context.Request["Save"]);
if (save)//是保存
{
string name = context.Request["Name"];
int age = Convert.ToInt32(context.Request["Age"]);
string email = context.Request["Email"];
sqlHelper.ExecuteNonQuery("Insert into Persons(Name,Age,Email) values(@Name,@Age,@Email)", new SqlParameter("@Name", name)
, new SqlParameter("@Age", age)
, new SqlParameter("@Email", email));
context.Response.Redirect("personlist.ashx");//保存成功返回列表頁面
}
else
{
//string html = CommonHelper.RenderHtml("PersonEdit.htm", new { Name = "", Age = 20, Email = "@rupeng.com" });
//定義匿名對象 Action可能與
數據庫中字段重復,建議分開,相干和無關的字段;New1個匿名類型,等于在1個匿名類中又創建1個匿名類,
var data = new { Action = "AddNew", Person = new { Name = "", Age = 20, Email = "@rupeng.com" } };
//進行渲染
string html = commonHelper.RenderHtml("personEdit.html", data);
context.Response.Write(html);
}
}
else if (action == "Edit")
{
//判斷是不是含有Save并且等于True,如果是的話說明點擊了保存按鈕
bool save = Convert.ToBoolean(context.Request["Save"]);
if (save)
{
//所有的信息
服務器端盡可能不要記,盡可能通過客戶端傳遞
//
服務器是1個忘記癥(無狀態),
服務器只認識Request中的信息
long id = Convert.ToInt64(context.Request["Id"]);
string name = context.Request["Name"];
int age = Convert.ToInt32(context.Request["Age"]);
string email = context.Request["Email"];
sqlHelper.ExecuteNonQuery("update Persons set Name=@Name,Age=@Age,Email=@Email where Id=@Id", new SqlParameter("@Id", id), new SqlParameter("@Name", name), new SqlParameter("@Age", age), new SqlParameter("@Email", email));
context.Response.Redirect("personlist.ashx");
}
else
{
long id = Convert.ToInt64(context.Request["Id"]);
DataTable dt = sqlHelper.ExecuteDataTable("select * from Persons where Id=@Id", new SqlParameter("@Id", id));
if (dt.Rows.Count <= 0)
{
context.Response.Write("沒有找到Id=" + id + "的數據");
}
else if (dt.Rows.Count > 1)
{
context.Response.Write("找到多條Id=" + id + "的數據");
}
else
{
DataRow row = dt.Rows[0];
var data = new { Action = "Edit", Person = row };
string html = commonHelper.RenderHtml("personEdit.html", data);
context.Response.Write(html);
}
}
}
else if (action == "Delete")
{
long id = Convert.ToInt64(context.Request["Id"]);
sqlHelper.ExecuteNonQuery("delete from Persons where Id=@Id", new SqlParameter("@Id",id));
context.Response.Redirect("personlist.ashx");
}
else
{
context.Response.Write("Action參數毛病!");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}</span></strong>
? 建立人員增刪改的渲染模板(personEdit.html)
<strong><span style="font-family:Microsoft YaHei;font-size:14px;"><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf⑻"/>
<title>
#if($Data.Action=="AddNew")
新增用戶
#else
編輯用戶$Data.Person.Name
#end
</title>
</head>
<body>
<form action="personEdit.ashx" method="post">
<!--<input type="hidden" name="Action" value="AddNew" />-->
<input type="hidden" name="Action" value="$Data.Action" />
<input type="hidden" name="Save" value="true" />
#if($Data.Action=="Edit")
<input type="hidden" name="Id" value="$Data.Person.Id" />
#end
<table style="background-color:blueviolet">
<tr><td>姓名:</td><td><input type="text" name="Name" value="$Data.Person.Name" /></td></tr>
<tr><td>年齡:</td><td><input type="text" name="Age" value="$Data.Person.Age" /></td></tr>
<tr><td>郵箱:</td><td><input type="text" name="Email" value="$Data.Person.Email" /></td></tr>
<tr><td></td><td><input type="submit" value="保存" /></td></tr>
</table>
</form>
</body>
</html>
</span></strong>
? 效果
列表顯示

點擊新增人員
點擊編輯
通過隱藏字段來實現想要的結果,在實現增刪改的頁面我們用了隱藏字段,隱藏字段是服務器端控件,這樣我們在服務器端可以通過隱藏字段的name來取得其相應的值,主要是由于關于1些操作這些是不要用戶可以看到的,只是程序需要看到,故而做成了隱藏字段。
至此我們就實現與數據庫的交互,出現的效果自己可以寫寫代碼看1下啊。
3. 總結
這樣總算完善了,不然總是覺得少了些甚么,自己最近時間緊,1直沒有寫這篇與數據庫交互的博客,在mvc中一樣存在1個引擎Razor,我們稱之為視圖引擎,希望在這篇博客的基礎能夠激起你對引擎探究的好奇心,自己去看看和研究吧,相信你會感興趣的。
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈