ASP.NET alert newline from CodeBehind

alert, asp.net, javascript, newline

Solution

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

Problem

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?

Original source