Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET alert newline from CodeBehind

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?

like image 744
Secret Avatar asked Mar 06 '13 19:03

Secret


2 Answers

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

like image 142
codingbiz Avatar answered Sep 28 '22 04:09

codingbiz


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.

like image 34
Oded Avatar answered Sep 28 '22 04:09

Oded