出自ProgWiki
用途
- 在用戶端顯示訊息,或顯示訊息後轉址。(根據該ASP.NET頁面上是否使用ToolkitScriptManager1來自動切換回傳JavaScript的方式)
程式碼
class CustomMessage
{
public static string JSStringEscape(string raw, bool inHtmlAttribute)
{
string raw2 = raw.Replace("\r\n", "\\n").Replace("\r", "").Replace("\n", "\\n");
if (inHtmlAttribute)
raw2 = raw2.Replace("\"", """).Replace("'", "\\'");
else
raw2 = raw2.Replace("'", "\\'").Replace("\"", "\\\"");
return raw2;
}
public static void Alert(Page thisPage, string strAlertMessage)
{
string strJS = string.Format(
@"<script type='text/javascript'>
/*<![CDATA[*/
alert('{0}');
/*]]>*/
</script>",
JSStringEscape(strAlertMessage, false));
string strKey = "CustomMessage_Alert";
if (thisPage.FindControl("ToolkitScriptManager1") == null)
{
thisPage.ClientScript.RegisterStartupScript(
typeof(string),
strKey,
strJS,
false);
}
else
{
AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(
thisPage,
typeof(string),
strKey,
strJS,
false);
}
}
public static void AlertAndRedirect(Page thisPage, int AlertNum, string strUrl)
{
string strJS = string.Format(
@"<script type='text/javascript'>
/*<![CDATA[*/
alert('{0}');
location.href='{1}';
/*]]>*/
</script>",
JSStringEscape(strAlertMessage, false),
strUrl);
string strKey = "CustomMessage_AlertAndRedirect";
if (thisPage.FindControl("ToolkitScriptManager1") == null)
{
thisPage.ClientScript.RegisterStartupScript(
typeof(string),
strKey,
strJS,
false);
}
else
{
AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(
thisPage,
typeof(string),
strKey,
strJS,
false);
}
}
}