[ASP.NET][C#][JavaScript][Message]網頁如何顯示/為何無法顯示錯誤訊息(Pop Up、Alert、Message Box)、

  • 1792
  • 0
  • 2018-03-30

須用JavaScript的Alert來達成。

基本用法是這樣:

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.ClientID, "喔喔,執行發生錯誤。", true);

但在訊息內容的地方,引用Exception Message,為什麼會沒顯示訊息呢?

點兩下瀏覽器左下方的驚嘆號三角形圖示,會看到錯誤訊息如下:

網頁錯誤詳細資料

使用者代理程式: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB6; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)
時間戳記: ...


訊息: 無法判定字串常數的結尾
行: 133
字元: 252
程式碼: 0
URI: http://localhost:......

如果用Debug模式去trace,會發現訊息當中有個"\n",這原是c#訊息的換行符號,但它會讓訊息無法正常顯示。

錯誤的寫法,直接用Exception Message,不會顯示Alert:

string sMsg = err.Message;
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.ClientID, string.Format("alert('{0}');", sMsg), true);

 把"\n"取代掉,就會顯示了:

string sMsg = err.Message.Replace("\r\n", "\n").Replace("\n", "");
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.ClientID, string.Format("alert('{0}');", sMsg), true);

但將"\n"取代成一個空字串,整串訊息變成一行,好像又太長了,有點難讀。

還是想要顯示成換行怎麼做呢?

把"\n"取代成"\\n"就行了。

完整做法如下:

try
{
	//Do Something...Select 資料表 發生錯誤
}
catch (Exception err)
{
	string sMsg = err.Message.Replace("\r\n", "\n").Replace("\n", "\\n");
	ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.ClientID, string.Format("alert('{0}');", sMsg), true);
}

再進一步處理另一個無法顯示訊息的狀況:

訊息: 必須要有 ')'

原因出在要顯示的Message裡面有單引號(') ,這個單引號包在Alert要顯示的文字裡,就變成總共4個單引號,最後一個括弧就被當作不存在,出現此錯誤。也就是:

Alert('資料來源沒有'def'欄位');

所以,再改程式碼,把單引號取代成雙引號如下:

try
{
	//Do Something...Select 資料表 發生錯誤
}
catch (Exception err)
{
	string sMsg = err.Message.Replace("\r\n", "\n").Replace("\n", "\\n").Replace("'", "\"");
	ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.ClientID, string.Format("alert('{0}');", sMsg), true);
}

※進一步把Show Message做成一個Mathod來呼叫:

private void ShowMessage(string message)
{
	string sMsg = message.Replace("\r\n", "\n").Replace("\n", "\\n").Replace("'", "\"");
	ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.ClientID, string.Format("alert('{0}');", sMsg), true);
}

呼叫這個Mathod:

try
{
	//Do Something...Select 資料表 發生錯誤
}
catch (Exception err)
{
	ShowMessage(err.Message);
}