Display literal string

L

Lucas

Hi,

I want to display an exception in a javascript alert and I'm rendering
that client code using

ClientScript.RegisterStartupScript(GetType(), key,
string.Format(@"<script>alert('ERROR:\r\n\r\n{0}');</script>",
ex.ToString()));

The problem is that ex.ToString() contains escape characters that not
appear literal in html.

For example:
"System.Data.SqlClient.SqlException: Cannot insert the value NULL into
column 'id_excepcion', table 'CI_Core.dbo.Tbl_GDC_Excepcion'; column
does not allow nulls. INSERT fails.\r\n at
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection)\r\n at
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection)\r\n at
System.Data.SqlClient......"

appears in html as:

"System.Data.SqlClient.SqlException: Cannot insert the value NULL into
column 'id_excepcion', table 'CI_Core.dbo.Tbl_GDC_Excepcion'; column
does not allow nulls. INSERT fails.
at System.Data.SqlClient.SqlConnection.OnError(SqlException
exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection)
at System.Data.SqlClient......."

causing an error in the javascript alert because the line breaks.

How can i put the ex.ToString() in html as literal?

Thanks!
 
A

Alberto Poblacion

Lucas said:
I want to display an exception in a javascript alert and I'm rendering
that client code using

ClientScript.RegisterStartupScript(GetType(), key,
string.Format(@"<script>alert('ERROR:\r\n\r\n{0}');</script>",
ex.ToString()));

The problem is that ex.ToString() contains escape characters that not
appear literal in html.

I pass the text of the exception through the following function, which I
don't claim to be optimal but gets the job done:

public static string EscapeText(string text)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (char c in text)
{
int asc = Convert.ToInt32(c);
if (asc >= 0x28 && asc <= 0x5b) sb.Append(c);
else if (asc >= 0x5d && asc <= 0x7e) sb.Append(c);
else
{
string hex = string.Format("{0:x}", asc);
if (hex.Length < 2) hex = "0" + hex;
sb.AppendFormat("\\x" + hex);
}
}
return sb.ToString();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top