Can't get Javascript to fire from c# codebehind - c#

I have read many posts here and many other sites and so I've gathered a few versions of HOW to do this. My problem is that I can't get it to do anything.
Here's the Javascript, just an alert for testing:
<script type="text/javascript">
function ICDcheck() {
alert('Patient has an ineligible diagnosis code!');
}
</script>
I tested this manually by adding the function to an OnClientClick of a button and it worked fine.
Here is what I've tried in the codebehind:
ClientScript.RegisterClientScriptBlock(this.GetType(), "uniqueKey", "ICDcheck()", true);
and...
string jsMethodName = "ICDcheck()";
ScriptManager.RegisterClientScriptBlock(this, typeof(string), "uniqueKey", jsMethodName, true);
and...
lblJavaScript.Text = "<script type='text/javascript'>ICDcheck();</script>";
This last one references a label I have sitting at the top of my asp : Content just below a script and the asp : ScriptManager block.
I've placed these bits in the button_click, the page_load, the sqldatasource_selecting, the formview_PageIndexChanging and always the same, nothing.
As always, thanks for your patience and help. My ignorance will likely be exposed as the problem, but I'm learning.

Try using Page.ClientScript :
Page.ClientScript.RegisterStartupScript( GetType(), "MyKey", "ICDcheck();", true);
Also install firebug and check if there are any script errors.

Try this. On your page, have a button:
<asp:Button ID="RunJsButton" runat="server" Text="Button" />
Then, in the code-behind, inject the script into the response and add the wireup to the button:
protected void Page_Load(object sender, EventArgs e)
{
string scriptToRun = #"function ICDcheck() { alert('Patient has an ineligible diagnosis code!');}";
ClientScript.RegisterClientScriptBlock(this.GetType(), "", scriptToRun, true);
RunJsButton.OnClientClick = "return ICDcheck();";
}
If that is the kind of thing you are after, you can refactor it a bit to implement best practice.

Try
<button ID="your_btn" onclick="javascript:your_function(); return false;"><asp:literal ID="your_literal" runat="server" /></button>
and
<script type="text/javascript">
function your_function() {
alert('Patient has an ineligible diagnosis code!');
}
</script>

This should work.
string jsToRun = "<script language=javascript>ICDcheck();</script>";
Type csType = this.GetType();
ClientScript.RegisterStartupScript(csType, "Key", jsToRun);

Related

RegisterStartUpScript does not fire javascript function

I am calling a JS function from Codebehind, the function is supposed to toggle() or show() a tr in the dom. I am using the following for this purpose:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), DateTime.Now.ToString(), "ToggleTr(1)", true);
If I am in a debugging mode, this works fine magically, but seems to work very spontaneously otherwise. Hence, I used a timeout 500 for this, but I believe that is not a good approach in itself. So my other try was:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), DateTime.Now.ToString(), "window.onload = function() {ToggleTr(1);}", true);
But this does not help either. NOTE: I am using webform aspx pages templated under a MasterPage, So I cannot use the head or a form tag either. This is what I have in my aspx page:
<asp:Panel ID="pnlEmployeeDetails" runat="server">
<script language="javascript" type="text/javascript">
function ToggleTr(showFlag) {
if (showFlag == 1) {
$("#trSupervisor").show();
}
else if (showFlag == 0) {
$("#trSupervisor").hide();
}
}
</script>
Secondly, I am not calling this on PageLoad, the calls vary on several event handlers executed.. What should I do here??

Alertify in a asp.net c# page

sorry if my english is poor.
I've a question, i think that the problem is my poor knowledge of javascript but.. i know that you can help me about this.
i've a page with an imagebutton, i use this for delete data and i need a confirmation dialog box. Alertify is pretty, i use altertify alert in server side like this:
string myScript2 = "alertify.error('message.')";
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(),
Guid.NewGuid().ToString(), myScript2, true);
return;
and work fine!
but i don't understand how to use alertify.confirm.
for example i've used
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="../../js/alertify.min.js"></script>
<!-- include the core styles -->
<link rel="stylesheet" href="../../js/alertify.core.css" />
<!-- include a theme, can be included into the core instead of 2 separate files -->
<link rel="stylesheet" href="../../js/alertify.default.css" />
<script type="text/javascript">
$("#btElimina").on('click', function () {
alertify.confirm("This is a confirm dialog", function (e) {
if (e) {
alertify.success("You've clicked OK");
} else {
alertify.error("You've clicked Cancel");
}
});
return false;
});
</script>
but nothing to do...i can't use onclientclick because alertify is a non-blocking instead a modal windows...
can you help me to understand? not to write code for me, but, to understand and make me viable
thank you
Henry
Replace alertify.success("You've clicked OK"); with return true;
and alertify.error("You've clicked Cancel"); with return false;
Also change this:
$("#btElimina").on('click', function () {
to this:
$("#<%=btElimina.ClientID%>").on('click', return function () {
I used this and it is working:
My button is :
<asp:ImageButton ToolTip="Çıkış" ID="ImageButton1" ImageUrl="Image/Exit.png" runat="server" OnClick="btnLogout_Click" />
My script is:
<script type="text/javascript">
$("#ImageButton1").on('click', function () {
alertify.confirm("This is a confirm dialog", function (e) {
if (e) {
alertify.success("You've clicked OK");
__doPostBack("<%=ImageButton1.UniqueID%>", "");
} else {
alertify.error("You've clicked Cancel");
}
});
return false;
});
</script>
Here when i clicked "cancel" button returns false and doing nothing but when you clicked ok button i am doing postback for related button and you can write your own code in server side
protected void btnLogout_Click(object sender, EventArgs e)
{
Session.RemoveAll();
Response.Redirect("~/Login.aspx");
...
}
I can't comment on the last comment below as I don't have 50 reputation, so I'm posting an answer simply to elaborate on Ratna's answer.
As per Ratna's answer, you should use server tags to refer to ASP.Net controls (controls with runat="server") to ensure that you get the control regardless of what ASP.Net renames the control to.
So to reiterate Ratna's answer:
Instead of
$('#btElimina').on(..
use
$('#<%= btElimina.ClientID %>').on(..
to make sure that you get the correct clientside control id in your jQuery script.

How can i determine PostBack value in window.onunload?

In our project we are deleting something after the user left the page. We are using window.unload event for doing this.
window.onunload = function() {
// delete something
}
We are generally using buttons, linkbuttons..etc in UpdatePanel so we hadn't needed to check Page.IsPostBack property.
Today we realized that we used some buttons out of UpdatePanel and this situation had produced some errors. After that we decided to change our method, defined a global variable (var _isPostBack = false), at the top of the our page and:
window.onunload = function() {
if (_isPostBack) {
_isPostBack = false;
return;
}
// delete something
}
Altought i set the g_isPostBack in Page_Load, g_isPostBack didn't change. I tried "RegisterClientScriptBlock", "RegisterOnSubmitStatement" and "RegisterStartupScript" methods. Register methods were called before the onunload event but _isPostBack was set after onunload event had triggered...
if (IsPostBack)
{
Control c = MyClass.GetPostBackControl(this);
bool inUpdatePanel = ControlParentForUpdatePanel(c);
if (!inUpdatePanel)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "_isPostBack = true;", true);
}
}
Is there anyone to help me?
that's the trick...
if you add onsubmit attribute to your form tag:
<form id="form1" onsubmit="return yourPostBack()">
and than write your own function:
function yourPostBack()
{
_isPostBack = true;
return true;
}
and finally in the page load:
if (IsPostBack)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "_isPostBack = false;", true);
}
with this method you can understand that it is postback or not, in window.onunload
I hope i am on the right track here,
As i understand,
the OnUnload() is ClientSide,
and therefore you don't have the server objects
what you can do... is save the value in a hidden field.
As i am used to PHP you can even embed the value in a Javascript variable
Dont know if this applys to ASP.NET:
<script language="javascript">
var MyServerVariable = "<?PHP echo MyServerVariable ?>"
if(MyServerVariable == "Blah...")
{
}
</script>
translates to
<script language="javascript">
var MyServerVariable = "VALUE"
if(MyServerVariable == "Blah...")
{
}
</script>
But same thing can be done with <asp:Label /> , i am sure...

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

I am having what I believe should be a fairly simple problem, but for the life of me I cannot see my problem. The problem is related to ScriptManager.RegisterStartupScript, something I have used many times before.
The scenario I have is that I have a custom web control that has been inserted into a page. The control (and one or two others) are nested inside an UpdatePanel. They are inserted onto the page onto a PlaceHolder:
<asp:UpdatePanel ID="pnlAjax" runat="server">
<ContentTemplate>
<asp:PlaceHolder ID="placeholder" runat="server">
</asp:PlaceHolder>
...
protected override void OnInit(EventArgs e){
placeholder.Controls.Add(Factory.CreateControl());
base.OnInit(e);
}
This is the only update panel on the page.
The control requires some initial javascript be run for it to work correctly. The control calls:
ScriptManager.RegisterStartupScript(this, GetType(),
Guid.NewGuid().ToString(), script, true);
and I have also tried:
ScriptManager.RegisterStartupScript(Page, Page.GetType(),
Guid.NewGuid().ToString(), script, true);
The problem is that the script runs correctly when the page is first displayed, but does not re-run after a partial postback. I have tried the following:
Calling RegisterStartupScript from CreateChildControls
Calling RegisterStartupScript from OnLoad / OnPreRender
Using different combinations of parameters for the first two parameters (in the example above the Control is Page and Type is GetType(), but I have tried using the control itself, etc).
I have tried using persistent and new ids (not that I believe this should have a major impact either way).
I have used a few breakpoints and so have verified that the Register line is being called correctly.
The only thing I have not tried is using the UpdatePanel itself as the Control and Type, as I do not believe the control should be aware of the update panel (and in any case there does not seem to be a good way of getting the update panel?).
Can anyone see what I might be doing wrong in the above?
Thanks :)
Well, to answer the query above - it does appear as if the placeholder somehow messes up the ScriptManager.RegisterStartupScript.
When I pull the control out of the placeholder and code it directly onto the page the Register script works correctly (I am also using the control itself as a parameter).
ScriptManager.RegisterStartupScript(this, GetType(), Guid.NewGuid().ToString(), script, true);
Can anyone throw any light on why an injected control onto a PlaceHolder would prevent the ScriptManager from correctly registering the script? I am guessing this might have something to do with the lifecycle of dynamic controls, but would appreciate (for my own knowledge) if there is a correct process for the above.
I had an issue using this in a user control (in a page this worked fine); the Button1 is inside an updatepanel, and the scriptmanager is on the usercontrol.
protected void Button1_Click(object sender, EventArgs e)
{
string scriptstring = "alert('Welcome');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertscript", scriptstring, true);
}
Now it seems you have to be careful with the first two arguments, they need to reference your page, not your control
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alertscript", scriptstring, true);
I think you should indeed be using the Control overload of the RegisterStartupScript.
I've tried the following code in a server control:
[ToolboxData("<{0}:AlertControl runat=server></{0}:AlertControl>")]
public class AlertControl : Control{
protected override void OnInit(EventArgs e){
base.OnInit(e);
string script = "alert(\"Hello!\");";
ScriptManager.RegisterStartupScript(this, GetType(),
"ServerControlScript", script, true);
}
}
Then in my page I have:
protected override void OnInit(EventArgs e){
base.OnInit(e);
Placeholder1.Controls.Add(new AlertControl());
}
Where Placeholder1 is a placeholder in an update panel. The placeholder has a couple of other controls on in it, including buttons.
This behaved exactly as you would expect, I got an alert saying "Hello" every time I loaded the page or caused the update panel to update.
The other thing you could look at is to hook into some of the page lifecycle events that are fired during an update panel request:
Sys.WebForms.PageRequestManager.getInstance()
.add_endRequest(EndRequestHandler);
The PageRequestManager endRequestHandler event fires every time an update panel completes its update - this would allow you to call a method to set up your control.
My only other questions are:
What is your script actually doing?
Presumably you can see the script in the HTML at the bottom of the page (just before the closing </form> tag)?
Have you tried putting a few "alert("Here");" calls in your startup script to see if it's being called correctly?
Have you tried Firefox and Firebug - is that reporting any script errors?
When you call ScriptManager.RegisterStartupScript, the "Control" parameter must be a control that is within an UpdatePanel that will be updated. You need to change it to:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), script, true);
The solution is to put the scripts in an outside js file (lets called 'yourDynamic.js') and re-register de file everytime you refresh the updatepanel.
I use this in the updatepanel_prerender event:
ScriptManager.RegisterClientScriptBlock(UpdatePanel1, UpdatePanel1.GetType(), "UpdatePanel1_PreRender", _
"<script type='text/javascript' id='UpdatePanel1_PreRender'>" & _
"include('yourDynamic.js');" & _
"removeDuplicatedScript('UpdatePanel1_PreRender');</script>" _
, False)
In the page or in some other include you will need this javascript:
// Include a javascript file inside another one.
function include(filename)
{
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
for(var x=0;x<scripts.length;> {
if (scripts[x].getAttribute('src'))
{
if(scripts[x].getAttribute('src').indexOf(filename) != -1)
{
head.removeChild(scripts[x]);
break;
}
}
}
script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.appendChild(script)
}
// Removes duplicated scripts.
function removeDuplicatedScript(id)
{
var count = 0;
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var firstScript;
for(var x=0;x<scripts.length;> {
if (scripts[x].getAttribute('id'))
{
if(scripts[x].getAttribute('id').indexOf(id) != -1)
{
if (count == 0)
{
firstScript = scripts[x];
count++;
}
else
{
head.removeChild(firstScript);
firstScript = scripts[x];
count = 1;
}
}
}
}
clearAjaxNetJunk();
}
// Evoids the update panel auto generated scripts to grow to inifity. X-(
function clearAjaxNetJunk()
{
var knowJunk = 'Sys.Application.add_init(function() {';
var count = 0;
var head = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var firstScript;
for(var x=0;x<scripts.length;> {
if (scripts[x].textContent)
{
if(scripts[x].textContent.indexOf(knowJunk) != -1)
{
if (count == 0)
{
firstScript = scripts[x];
count++;
}
else
{
head.removeChild(firstScript);
firstScript = scripts[x];
count = 1;
}
}
}
}
}
Pretty cool, ah...jejeje
This part of what i posted some time ago here.
Hope this help... :)
I had an issue with Page.ClientScript.RegisterStartUpScript - I wasn't using an update panel, but the control was cached. This meant that I had to insert the script into a Literal (or could use a PlaceHolder) so when rendered from the cache the script is included.
A similar solution might work for you.
DO NOT Use GUID For Key
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel)
Guid.NewGuid().ToString(), myScript, true);
and if you want to do that , call Something Like this function
public static string GetGuidClear(string x)
{
return x.Replace("-", "").Replace("0", "").Replace("1", "")
.Replace("2", "").Replace("3", "").Replace("4", "")
.Replace("5", "").Replace("6", "").Replace("7", "")
.Replace("8", "").Replace("9", "");
}
What worked for me, is registering it on the Page while specifying the type as that of the UpdatePanel, like so:
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel) Guid.NewGuid().ToString(), myScript, true);
Sometimes it doesnt fire when the script has some syntax error, make sure the script and javascript syntax is correct.
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(),script, true );
The "true" param value at the end of the ScriptManager.RegisterStartupScript will add a JavaScript tag inside your page:
<script language='javascript' defer='defer'>your script</script >
If the value will be "false" it will inject only the script witout the --script-- tag.
I try many things and finally found that the last parameter must be false and you must add <SCRIPT> tag to the java script :
string script = "< SCRIPT >alert('hello!');< /SCRIPT>";
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), key, script, **false**);

Response.Redirect to new window

I want to do a Response.Redirect("MyPage.aspx") but have it open in a new browser window. I've done this before without using the JavaScript register script method. I just can't remember how?
I just found the answer and it works :)
You need to add the following to your server side link/button:
OnClientClick="aspnetForm.target ='_blank';"
My entire button code looks something like:
<asp:LinkButton ID="myButton" runat="server" Text="Click Me!"
OnClick="myButton_Click"
OnClientClick="aspnetForm.target ='_blank';"/>
In the server side OnClick I do a Response.Redirect("MyPage.aspx"); and the page is opened in a new window.
The other part you need to add is to fix the form's target otherwise every link will open in a new window. To do so add the following in the header of your POPUP window.
<script type="text/javascript">
function fixform() {
if (opener.document.getElementById("aspnetForm").target != "_blank") return;
opener.document.getElementById("aspnetForm").target = "";
opener.document.getElementById("aspnetForm").action = opener.location.href;
}
</script>
and
<body onload="fixform()">
You can use this as extension method
public static class ResponseHelper
{
public static void Redirect(this HttpResponse response, string url, string target, string windowFeatures)
{
if ((String.IsNullOrEmpty(target) || target.Equals("_self", StringComparison.OrdinalIgnoreCase)) && String.IsNullOrEmpty(windowFeatures))
{
response.Redirect(url);
}
else
{
Page page = (Page)HttpContext.Current.Handler;
if (page == null)
{
throw new InvalidOperationException("Cannot redirect to new window outside Page context.");
}
url = page.ResolveClientUrl(url);
string script;
if (!String.IsNullOrEmpty(windowFeatures))
{
script = #"window.open(""{0}"", ""{1}"", ""{2}"");";
}
else
{
script = #"window.open(""{0}"", ""{1}"");";
}
script = String.Format(script, url, target, windowFeatures);
ScriptManager.RegisterStartupScript(page, typeof(Page), "Redirect", script, true);
}
}
}
With this you get nice override on the actual Response object
Response.Redirect(redirectURL, "_blank", "menubar=0,scrollbars=1,width=780,height=900,top=10");
Contruct your url via click event handler:
string strUrl = "/some/url/path" + myvar;
Then:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "window.open('" + strUrl + "','_blank')", true);
Because Response.Redirect is initiated on the server you can't do it using that.
If you can write directly to the Response stream you could try something like:
response.write("<script>");
response.write("window.open('page.html','_blank')");
response.write("</script>");
The fixform trick is neat, but:
You may not have access to the code
of what loads in the new window.
Even if you do, you are depending on
the fact that it always loads, error
free.
And you are depending on the fact
that the user won't click another
button before the other page gets a
chance to load and run fixform.
I would suggest doing this instead:
OnClientClick="aspnetForm.target ='_blank';setTimeout('fixform()', 500);"
And set up fixform on the same page, looking like this:
function fixform() {
document.getElementById("aspnetForm").target = '';
}
You can also use in code behind like this way
ClientScript.RegisterStartupScript(this.Page.GetType(), "",
"window.open('page.aspx','Graph','height=400,width=500');", true);
This is not possible with Response.Redirect as it happens on the server side and cannot direct your browser to take that action. What would be left in the initial window? A blank page?
popup method will give a secure question to visitor..
here is my simple solution: and working everyhere.
<script type="text/javascript">
function targetMeBlank() {
document.forms[0].target = "_blank";
}
</script>
<asp:linkbutton runat="server" ID="lnkbtn1" Text="target me to blank dude" OnClick="lnkbtn1_Click" OnClientClick="targetMeBlank();"/>
<asp:Button ID="btnNewEntry" runat="Server" CssClass="button" Text="New Entry"
OnClick="btnNewEntry_Click" OnClientClick="aspnetForm.target ='_blank';"/>
protected void btnNewEntry_Click(object sender, EventArgs e)
{
Response.Redirect("New.aspx");
}
Source: http://dotnetchris.wordpress.com/2008/11/04/c-aspnet-responseredirect-open-into-new-window/
If you can re-structure your code so that you do not need to postback, then you can use this code in the PreRender event of the button:
protected void MyButton_OnPreRender(object sender, EventArgs e)
{
string URL = "~/MyPage.aspx";
URL = Page.ResolveClientUrl(URL);
MyButton.OnClientClick = "window.open('" + URL + "'); return false;";
}
You can also use the following code to open new page in new tab.
<asp:Button ID="Button1" runat="server" Text="Go"
OnClientClick="window.open('yourPage.aspx');return false;"
onclick="Button3_Click" />
And just call Response.Redirect("yourPage.aspx"); behind button event.
I always use this code...
Use this code
String clientScriptName = "ButtonClickScript";
Type clientScriptType = this.GetType ();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager clientScript = Page.ClientScript;
// Check to see if the client script is already registered.
if (!clientScript.IsClientScriptBlockRegistered (clientScriptType, clientScriptName))
{
StringBuilder sb = new StringBuilder ();
sb.Append ("<script type='text/javascript'>");
sb.Append ("window.open(' " + url + "')"); //URL = where you want to redirect.
sb.Append ("</script>");
clientScript.RegisterClientScriptBlock (clientScriptType, clientScriptName, sb.ToString ());
}
Here's a jQuery version based on the answer by #takrl and #tom above. Note: no hardcoded formid (named aspnetForm above) and also does not use direct form.target references which Firefox may find problematic:
<asp:Button ID="btnSubmit" OnClientClick="openNewWin();" Text="Submit" OnClick="btn_OnClick" runat="server"/>
Then in your js file referenced on the SAME page:
function openNewWin () {
$('form').attr('target','_blank');
setTimeout('resetFormTarget()', 500);
}
function resetFormTarget(){
$('form').attr('target','');
}
I used Hyperlink instead of LinkButton and it worked just fine, it has the Target property so it solved my problem. There was the solution with Response.Write but that was messing up my layout, and the one with ScriptManager, at every refresh or back was reopening the window. So this is how I solved it:
<asp:HyperLink CssClass="hlk11" ID="hlkLink" runat="server" Text='<%# Eval("LinkText") %>' Visible='<%# !(bool)Eval("IsDocument") %>' Target="_blank" NavigateUrl='<%# Eval("WebAddress") %>'></asp:HyperLink>
You may want to use the Page.RegisterStartupScript to ensure that the javascript fires on page load.
you can open new window from asp.net code behind using ajax like I did here
http://alexandershapovalov.com/open-new-window-from-code-behind-in-aspnet-68/
protected void Page_Load(object sender, EventArgs e)
{
Calendar1.SelectionChanged += CalendarSelectionChanged;
}
private void CalendarSelectionChanged(object sender, EventArgs e)
{
DateTime selectedDate = ((Calendar) sender).SelectedDate;
string url = "HistoryRates.aspx?date="
+ HttpUtility.UrlEncode(selectedDate.ToShortDateString());
ScriptManager.RegisterClientScriptBlock(this, GetType(),
"rates" + selectedDate, "openWindow('" + url + "');", true);
}
None of the previous examples worked for me, so I decided to post my solution. In the button click events, here is the code behind.
Dim URL As String = "http://www.google/?Search=" + txtExample.Text.ToString
URL = Page.ResolveClientUrl(URL)
btnSearch.OnClientClick = "window.open('" + URL + "'); return false;"
I was having to modify someone else's response.redirect code to open in a new browser.
I used this approach, it doesn't require you to do anything on the popup (which I didn't have access to because I was redirecting to a PDF file). It also uses classes.
$(function () {
//--- setup click event for elements that use a response.redirect in code behind but should open in a new window
$(".new-window").on("click", function () {
//--- change the form's target
$("#aspnetForm").prop("target", "_blank");
//--- change the target back after the window has opened
setTimeout(function () {
$("#aspnetForm").prop("target", "");
}, 1);
});
});
To use, add the class "new-window" to any element. You do not need to add anything to the body tag. This function sets up the new window and fixes it in the same function.
I did this by putting target="_blank" in the linkbutton
<asp:LinkButton ID="btn" runat="server" CausesValidation="false" Text="Print" Visible="false" target="_blank" />
then in the codebehind pageload just set the href attribute:
btn.Attributes("href") = String.Format(ResolveUrl("~/") + "test/TestForm.aspx?formId={0}", formId)
HTML
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" OnClientClick = "SetTarget();" />
Javascript:
function SetTarget() {
document.forms[0].target = "_blank";}
AND codebehind:
Response.Redirect(URL);

Categories