摘要:[ASP.NET] 讓 Show 訊息變簡單
Introduction
自己在練習寫 web 程式,有時候可能需要印出一些值或是 show 出訊息,來檢視程式的正確性。
一開始都是組 javascript alert 字串,後來知道 asp.net 有提供一些方法,透過封裝或是模組化,
用起來還滿方便的,介紹給大家我的用法。
Example
sample1
將 show 字串的功能函式寫在 PageBase 中,這樣每一個繼承的子 page ,都可以使用。
public partial class PageBase : System.Web.UI.Page {
protected void ShowMsg(string value) {
ClientScriptManager oCSM = Page.ClientScript;
Random oRandom = new Random();
string scriptkey = oRandom.Next(1000).ToString();
oCSM.RegisterStartupScript(this.Page.GetType(), scriptkey, "alert('" + value + "');", true);
}
}
Client 端用法:
public partial class Default : PageBase {
protected void Page_Load(object sender, EventArgs e) {
ShowMsg("Test");
}
}
輸出結果:
sample2
將這個功能抽出,成為組件的一部分。
using System.Web.UI;
public class TWMsg {
public static void ShowMsg(System.Web.UI.Page ActPage,string value) {
//取得 ClientScriptManager 物件。
ClientScriptManager oCSM = ActPage.ClientScript;
//建立亂數 scriptkey 。
Random oRandom = new Random();
string scriptkey = oRandom.Next(1000).ToString();
//印出訊息,這邊 scriptkey 參數給定 null 值,也是可以正常執行的
oCSM.RegisterStartupScript(ActPage.GetType(), scriptkey, "alert('" + value + "');", true);
}
}
Client 端程式碼:
public partial class Default : PageBase {
protected void Page_Load(object sender, EventArgs e) {
TWMsg.ShowMsg(this.Page, "DefaultPage");
}
}
輸出結果:
修正:
v1.2 : 加入 Microsoft Anti-Cross Site Scripting Library v3.1
撰寫 TMsgBox 類別
using System.Web.UI;
using Microsoft.Security.Application;
namespace TestMsgBox {
public class TMsgBox {
public static void ShowMsg(System.Web.UI.Page ActPage, string value) {
TMsgBox oTMsgBox = new TMsgBox();
oTMsgBox.ProcessShowMsg(ActPage, value);
}
private void ProcessShowMsg(System.Web.UI.Page ActPage, string value) {
TMsgBox oTMsgBox = new TMsgBox();
string sResult = string.Empty;
sResult = oTMsgBox.FilterAndEncodeStr(value);
oTMsgBox.RegisterStartupScript(ActPage, sResult);
}
private string FilterAndEncodeStr(string value) {
string sFilterValue = string.Empty;
sFilterValue = value;
//過濾 HTML 字串。
sFilterValue = AntiXss.GetSafeHtmlFragment(sFilterValue);
//將字串進行編碼。
sFilterValue = AntiXss.JavaScriptEncode(sFilterValue);
return sFilterValue;
}
private void RegisterStartupScript(System.Web.UI.Page ActPage, string value) {
Random oRandom = new Random();
string scriptkey = oRandom.Next(1000).ToString();
ClientScriptManager oCSM = ActPage.ClientScript;
oCSM.RegisterStartupScript(ActPage.GetType(), scriptkey, @"alert(" + value + @");", true);
}
}
}
PgaeBase code :
public partial class PageBase : System.Web.UI.Page {
protected void ShowMsg(string value) {
TMsgBox.ShowMsg(Page, value);
}
}
page code :
public partial class Page : PageBase {
protected void Page_Load(object sender, EventArgs e) {
//測試輸入字串
string s = @" 'My Name is Page.' ";
ShowMsg(s);
}
}
輸出結果
問
若輸出的字串需要換行,可是 AntiXss.GetSafeHtmlFragment(sFilterValue); 函式,
又會將 \r\n 濾掉,不知有沒有解決方法。
Link
Microsoft Anti-Cross Site Scripting Library V3.1 下載
三小俠 小弟獻醜,歡迎指教


