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

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 ^

Related

Pop window not opening at code behind

After open pop window, i need to reload my page. here page gets reloaded but pop window not opened. How to solve it.
string url = "Popup.aspx";
string s = "window.open('" + url + "', 'popup_window', 'width=300,height=100,left=100,top=100,resizable=yes');";
ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);
Response.Redirect("~/mysamepage.aspx", false);
Have you tried a Reload in the javascript by appending it to the s string:
window.location.reload(false);
// If you need to fetch the webpage from the web-server again (where the page
//contents change dynamically) pass the argument as 'true' instead of 'false'.
eg
string s = "window.open('" + url + "', 'popup_window', 'width=300,height=100,left=100,top=100,resizable=yes');window.location.reload(false);";
or try:
window.opener.href('url').reload(true);

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);

Opening a PDF with search parameters just opens the PDF

I was requested to add some searching functionality to an existing system for the collection of PDFs that we have. I know about searching PDFs and opening them with search parameters and in a test application I wrote, it works like a dream. When trying to convert it over to our existing application the PDF opens but without the search terms or the advanced find of Acrobat Reader popping up. Any help would be greatly appreciated!
Here is a snippet of the cs code :
case "PDF":
string searchTerms = SearchWordsTB.Text;
searchTerms = searchTerms.Replace(',', ' ');
launchStr = "OpenPDF('" + e.Row.Cells[9].Text.Replace("\\", "/") + "','" + HttpUtility.UrlEncode(e.Row.Cells[2].Text) + "','" + e.Row.Cells[0].Text + "','" + searchTerms + "')";
break;
We are creating the list of documents on the fly and PDF is one of the options. Assuming I am understanding this correctly, A DataGrid is created with all these clickable rows that will execute a Javascript function when clicked. The Javascript function OpenPDF is shown below:
function OpenPDF(url, filename, ID, searchTerms) {
if (searchTerms.length > 0) {
window.open('FileViewer.aspx?name=' + filename + '&ID=' + ID + '&url=' + url + '#search="' + searchTerms + '"', 'mywindow' + windowCnt, 'width=800,height=600,location=no,resizable=yes');
}
else {
window.open('FileViewer.aspx?name=' + filename + '&ID=' + ID + '&url=' + url, 'mywindow' + windowCnt, 'width=800,height=600,location=no,resizable=yes');
}
windowCnt++;
}
From following the debugging in the CS code, I know that I am properly stripping out the commas in the search terms so that shouldn't be the problem. What currently happens is the PDF file will open up just fine, but the search terms are not being used. I have tried following the debugger through the Javascript (which for me has always been spotty at best) but the breakpoint is never hit. It should also probably be noted that the Javascript function is kept in a separate Javascript File and is not inline in the aspx page. And yes, we are correctly referencing the Javascript file. I will be more than happy to update this post with any extra info that is requested. Thanks in advance for any help!
I was able to achieve the desired results by using the http encode on the launch string as shown below.
launchStr = "OpenFile('" + HttpUtility.UrlEncode(e.Row.Cells[9].Text.Replace("\\", "/") + "#search=\"" + searchTerms + "\"") + "','" + HttpUtility.UrlEncode(e.Row.Cells[2].Text) + "','" + e.Row.Cells[0].Text + "','" + e.Row.Cells[1].Text + "')";
I then used the function to just open the window with the PDF in it. The problem I had was that without the HTTP Encode, the URL was just cutting off the search parameters. I believe this is because the #search="blah" isn't normally recognized as part of a URL and was therefore truncated. If anyone has a better reason, I would love to hear it.

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);

ASP.Net C# JavaScript Popup Window Help

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);

Categories