ASP.Net C# JavaScript Popup Window Help - c#

I've looked all over the place and had very little luck.
try{
FooError();
}
catch (Exception Exc){
ClientScript.RegisterClientScriptBlock(this.GetType(), "errorPop",
#"<script language='javascript'> alert(" + Exc.Message + "); </script>");
return;
}
I keep getting a javascript error saying "Expected a ')'.". I've tried the script with a # at the start (like it is), without a # at the start, with and without a semicolon at the end. I've tried
ClientScript.RegisterClientScriptBlock(this.GetType(), "errorPop",
#"<script type=\"text/javascript\"> alert(" + Exc.Message + "); </script>");
I've been able to get this to work with a static value in the alert function
ClientScript.RegisterClientScriptBlock(this.GetType(), "errorPop",
#"<script language='javascript'> alert('Foo'); </script>");
But that's not what I need.
What am I doing wrong here? Is there a better way?
I guess what I mean to ask is how do you use a C# string variable in a JavaScript alert box, if it's even possible.
Thanks.
This is my first question I hope I did it right -.-;

Sounds like there may be some characters in your Exc.Message that break the javascript string. Look at your source to see what's generated, but I'd expect to find something like this:
<script language='javascript'> alert("Error "this" happened"); </script>
Notice how the "this" would break that. So you'd need to do something like
Exc.Message.Replace("\"", "'");

add quotes around the Exc.Message -- like you did with Foo.
ClientScript.RegisterClientScriptBlock(this.GetType(), "errorPop",
#"<script type=\"text/javascript\"> alert('" + Exc.Message + "'); </script>");
or
ClientScript.RegisterClientScriptBlock(this.GetType(), "errorPop",
#"<script type=\"text/javascript\"> alert(\"" + Exc.Message + "\"); </script>");
Because your output would look like this
alert(whatever the message is);

Related

Response.Redirect not sending string

i've got a bit of a problem trying to set up a general error page in MVC.
I am handling all app errors in Global.asax.cs with the following code ->
protected void Application_Error(object sender, EventArgs e)
{
//if (Request.Url.ToString().StartsWith("http://localhost:"))
// return;
string msg;
Exception ex = Server.GetLastError().GetBaseException();
StringBuilder sb = new StringBuilder();
sb.AppendLine("Exception Found");
sb.AppendLine("Timestamp: " + System.DateTime.Now.ToString());
sb.AppendLine("Error in: " + Request.Url.ToString());
sb.AppendLine("Browser Version: " + Request.UserAgent.ToString());
sb.AppendLine("User IP: " + Request.UserHostAddress.ToString());
sb.AppendLine("Error Message: " + ex.Message);
sb.AppendLine("Stack Trace: " + ex.StackTrace);
msg = sb.ToString();
Server.ClearError();
Response.Redirect(string.Format("~/Error/Error?w={0}", msg ));
}
My problem is that i'm not getting a redirect. I see the same page URL and a blank page when i'm creating an error.
If i remove "errorMsg" and add a SIMPLE STRING, it works, redirects with the required param. Ex:
string test = "testme";
Response.Redirect(string.Format("~/Error/Error?w={0}", test));
That does redirect me to the error page with param "testme". What am i doing wrong here?
You to need escape all the parameters (UrlEncode). At the moment it is unescaped and has a whole bunch of new lines too.
Before you do that, I suggest you just append "hello world" parameter and re-display that to ensure your redirect page is working

opening multiple browser tabs but only one will open

I have a scenario where I loop through a data set (max of 6 records) and then open a new browser tab for each record - each tab shows an invoice for one of the records - not the best design but it's what was requested.
I'm using the code below within a foreach to build a url and open a new browser tab, the problem is it loops through ok but only ever opens 1 new tab.
Every other thing happening in the loop works so the problem seems to be with the code. It opens the first tab for the first record then no more after that.
Can anyone comment on what's wrong?
string pageurl = "Label.aspx?booking=" + v.booking + "&pallet=" + v.palletId;
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "window.open('" + pageurl + "','_blank')", true);
You can only have one startup script. Try putting all of your window.open calls in a single script;
//This code inside loop
string pageurl = "Label.aspx?booking=" + v.booking + "&pallet=" + v.palletId;
string script += "window.open('" + pageurl + "','_blank'); "
//This code outside loop
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", script, true);

RegisterStartupScript Alert Error when carriage return is in the string

I have RegisterStartupScript in the code-behind class to alert error message -- it works fine except when the error has line feeds or carriage returns (I think). Here is the snippet:
The commented code works fine!
catch (Exception ex)
{
//Page.ClientScript.ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Failure", "alert('ERROR: '), true);
Page.ClientScript.RegisterStartupScript(this.GetType(), "System Error", "alert('" + ex.Message.Replace("'", "\\'") + "');", true);
}
Line terminators are not allowed in js strings.
Eliminate the line terminators (carriage returns, new line symbols etc.) using regular expressions:
var errorMsg = Regex.Replace(ex.Message,
#"[\u000A|\u000D|\u2029\u2028|\u000D\u000A]", " ");
Page.ClientScript.RegisterStartupScript(this.GetType(), "System Error",
String.Format("alert('{0}');", errorMsg), true);

Why I can't register a client script block of string (url)?

Code :
string url = "http://www.google.com";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "UrlSocialDefinitivo", "var UrlSocialDefinitivo=" + Server.UrlEncode(url) + ";", true);
but I get (on browser console) : SyntaxError: identifier starts immediately after numeric literal.
In fact it registers UrlSocialDefinitivo=http%3a%2f%2fwww.google.it;
Where am I wrong? How can I resolve this trouble?
It miss the quotes around the string :
string url = "http://www.google.com";
ScriptManager.RegisterClientScriptBlock(
this,
this.GetType(),
"UrlSocialDefinitivo",
"var UrlSocialDefinitivo=\"" + Server.UrlEncode(url) + "\";",
true
);
That will produces :
UrlSocialDefinitivo="http%3a%2f%2fwww.google.it";
Note that I'm not sure you have to keep the Server.UrlEncore call. It depends on the format you are expecting actually.
You need to surround the url string in quotes or the javascript interpreter will assume it is javascript to be executed (and fail miserably).
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"UrlSocialDefinitivo",
"var UrlSocialDefinitivo='" + Server.UrlEncode(url) + "';", true);
// quotes here ^ and here ^

Display exception message through javascript alert in asp.net

I am trying to show exception message through javascript alert box.
Here is the sample code.
public static void HandleException(Page page, Exception ex)
{
string message = ex.Message.ToString();
ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "", "alert('"+message+"');", true);
}
It runs if i give literal values for the string variable.
e.g.
string message = "Hello World";
But it fails if I give message = ex.Message;
Any Idea?
You need to encode it, for example using JavaScriptSerializer because if the message contains some escape characters like ' or " this will definitely break your javascript:
var message = new JavaScriptSerializer().Serialize(ex.Message.ToString());
var script = string.Format("alert({0});", message);
ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "", script, true);
try
{
//do some thing
}
catch (Exception ex)
{
Response.Write("<script language='javascript'>alert('" +
Server.HtmlEncode(ex.Message) + "')</script>");
}
Does your ex.Message have any ' characters in it? They may need escaping.

Categories