I have such code in Page.aspx.cs file:
void btnSessionCreate_Click(object sender, EventArgs e)
{
if (Session["user"] == null)
{
Session["user"] = Guid.NewGuid().ToString();
Response.Redirect("/");
}
else if (Session["user"] != null)
{
string userBrowser = Request.UserAgent.ToString();
string sessionId = Session["user"].ToString();
Response.Write("<script>alert('" + sessionId + "\r\n" + userBrowser + "');</script>");
}
}
The main problem is "\r\n" part in Response.Write() method. I wanted to separate data with a newline, but can't!
If there is not "\r\n" , script alerts well, but if exists in code nothing is alerting and is changing resets its CSS style.
Why?
Use the @
symbol or double \\
to escape the slash
string script = String.Format(@"<script>alert('{0}\r\n{1}');</script>", sessionId, userBrowser);
OR
string script = String.Format("<script>alert('{0}\\r\\n{1}');</script>", sessionId, userBrowser);
Client.RegisterStartupScript(this.GetType(), "myscript", script, true);
More info on Client.RegisterStartupScript here
You just need to escape the \
, so they become \
when output to JavaScript:
Response.Write("<script>alert('" + sessionId + "\\r\\n" + userBrowser + "');</script>");
Or:
Response.Write("<script>alert('" + sessionId + @"\r\n" + userBrowser + "');</script>");
You are in a C# context in the above line, so \r\n
is interpreted as a new line that needs to be output by Response.Write
. that's not what you want. You want the literal \r\n
to be output, so they are interpreted as JavaScript newlines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With