ASP.NET Error Message from CodeBehind

I have this code in the 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" in the Response.Write () method. I wanted to share data with a new line, but I can’t!

If "\ r \ n" does not exist, the script warns well, but if it exists in the code, it does not warn anything and changes to reset its CSS style.

Why?

+6
source share
3 answers

Use the @ or double \\ character to remove 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); 

Learn more about Client.RegisterStartupScript here

+6
source

You just need to avoid \ so that they become \ when outputting to JavaScript:

 Response.Write("<script>alert('" + sessionId + "\\r\\n" + userBrowser + "');</script>"); 

Or:

 Response.Write("<script>alert('" + sessionId + @"\r\n" + userBrowser + "');</script>"); 

You are in the C # context in the line above, so \r\n interpreted as a new line, which should be output to Response.Write . this is not what you want. You want the literal \r\n be output, so they are interpreted as new JavaScript lines.

+1
source

Response.Write ("alert ('" + sessionId + "\ n" + userBrowser + "');");

this will work fine in asp.net

0
source

All Articles