How to dynamically create and add textbox to a placeholder using AJAX? - c#

I'm trying to create text box dynamically. so I cal it through the AJAX function.
This is my code:
Ajax function
function ChangedAdults(noofAdults) {
alert(noofAdults.value);
$.ajax({
type: 'POST',
dataType: 'json',
url: "/FlightBooking.aspx/Adults",
data: "{noOfAdults:'" + noofAdults.value + "'}",
contentType: "application/json; charset=utf-8",
success: function (result) {
$("#AdultsList").html(result.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
code behind
[WebMethod]
public static string Adults(int noOfAdults)
{
FlightBooking obj = new FlightBooking();
obj.CreateAdultsList(noOfAdults);
string test= "";
return test.ToString();
}
private void CreateAdultsList(int noOfAdults)
{
int n = noOfAdults;
for (int i = 0; i < n; i++)
{
TextBox MyTextBox = new TextBox();
MyTextBox.ID = "tb" + "" + i;
AdultsListPlaceholder.Controls.Add(MyTextBox); //error coming here
AdultsListPlaceholder.Controls.Add(new LiteralControl("<br />"));
}
}
But I receive an error:
Object reference not set to an instance of an object
What could cause this problem?

You can not dynamically add controls to a page using JQuery AJAX. Please get a good understanding of asp.net page lifecycle
In short this is how asp.net pages work.
Browswer sends request to server. i.e. http://localhost/test.aspx
Server creates a object for the page class. In this case the class is Test
The object renders the page. That means it converts the Controls of test.aspx to HTML which browsers can understand.
Server sends the rendered HTML back to Browser and destroys the object.
Browser displays the page.
So the server creates a new object every time it receives a page request.
However when a call to WebMethods is made using AJAX, no page object is created. This is why Webmethods have to be static.
I can see you are trying to create a object yourself and add the dynamic controls to that object. But this object is not related to the content displayed in the browser. So, adding controls to this object won't change anything that's displayed in the browser. For that to happen you have to post the whole page back. And if you return the rendered output of the object you created with Response.Write, that will return the HTML version of the whole page. Which is basically same as a PostBack
However, you can achieve AJAX based dynamic control rendering using UpdatePanel. Below is one way to do it
ASPX page
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="btnCreate" runat="server" Text="Create" OnClick="btnCreate_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="btnRead" runat="server" Text="Read" OnClick="btnRead_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
Code Behind
protected int NumberOfControls
{
get { return Convert.ToInt32(Session["noCon"]); }
set { Session["noCon"] = value.ToString(); }
}
private void Page_Init(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
//Initiate the counter of dynamically added controls
this.NumberOfControls = 0;
else
//Controls must be repeatedly be created on postback
this.createControls();
}
private void Page_Load(object sender, System.EventArgs e)
{
}
protected void btnCreate_Click(object sender, EventArgs e)
{
TextBox tbx = new TextBox();
tbx.ID = "txtData"+NumberOfControls;
NumberOfControls++;
PlaceHolder1.Controls.Add(tbx);
}
protected void btnRead_Click(object sender, EventArgs e)
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++)
{
TextBox tx = (TextBox)PlaceHolder1.FindControl("txtData" + i.ToString());
//Add the Controls to the container of your choice
Label1.Text += tx.Text + ",";
}
}
private void createControls()
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++)
{
TextBox tx = new TextBox();
tx.ID = "txtData" + i.ToString();
//Add the Controls to the container of your choice
PlaceHolder1.Controls.Add(tx);
}
}
Hope this helps.

You're mixing your paradigms. What would you expect this code to do? You can render controls in response to an AJAX call, but you must then manually insert the processed HTML into the DOM.
Call server using AJAX
Instantiate a dummy page container
Render server control
Return markup
Insert into DOM
Or, you can add new controls in response to a server event via a full postback or an async postback (e.g. an UpdatePanel).

In asp.net you can not create server control from jQuery or java-script.
Though you can call web-method from jQuery but you can't add any control from web method.
More details
Add new ASP.NEt server controls with jQuery?
One of the idea it to create textbox is to create html textbox
<input type="text" id="text1" ></input>
And post your value through jQuery ajax for manipulation.
Edit 1
Other way is to create all the controls at page load (If you know the maximum number)
Hide them initially
Show one by one on button click
And get the value on the server after postback.
Example:
add text to an asp.net textbox control with jQuery

AdultsListPlaceholder is null, you need to override its onload function to create children of this control.
e.g.
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
CreateAdultsList(5);
}

Related

How to store/restore table with dynamic elements in view state in c# asp web aplication

I am new to concept of web app with dynamic content.
I am creating simple app that take information (steps for a test) from database and adds rows to table (every row is containing, two labels, two radio buttons and text field).
It works like this:
1. I have a page with text box and button,
2. I put test ID to retrieve test steps, then click submit button
3. Based on number of steps I add a row to table for every step, so I have table that looks like this:
[Label.text="Step1"][RadioButtonPass][RadioButtonFail][Label.Text="Comment:"][TextBox]
[Label.text="Step2"][RadioButtonPass][RadioButtonFail][Label.Text="Comment:"][TextBox]
[Label.text="Step3"][RadioButtonPass][RadioButtonFail][Label.Text="Comment:"][TextBox]
etc.
When user press every radio button he can click submitResult button and data are send to db.
Page is genereting correctly but I am having trouble with dynamic content because when I hit submitResult button table is empty again (at this point submitResult button do nothing). I read about it and I think I need to store table into View State. How can I do it?
I tried to save table to
ViewState[table.ID] = table;
at the end of PopulateTable method and then restore it in
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ViewState[TableForMethods.ID] != null)
{
TableForMethods = (Table)ViewState[TableForMethods.ID];
}
}
}
but that doesn't work.
My code looks like this:
*.aspx
<body style="height: 510px">
<form id="form1" runat="server">
<p>
Put test case ID and submit
</p>
<asp:TextBox ID="TextBoxId" runat="server">1804673290</asp:TextBox>
<asp:Button ID="ButtonRetriveId" runat="server" OnClick="ButtonSubmitId_Click" Text="Submit" Width="81px" />
<p>
</p>
<p>
<asp:Label ID="LabelMethods" runat="server"></asp:Label>
</p>
<p>
<asp:Table ID="TableForMethods" runat="server">
</asp:Table>
</p>
<div style="text-align: right">
<asp:Button ID="ButtonSubmitResults" runat="server" Text="Submit result" OnClick="ButtonSubmitResults_Click" Visible="False" />
</div>
<div style="text-align: right; position: absolute; bottom: 0px">
<asp:Label ID="LabelStatus" runat="server"></asp:Label>
</div>
</form>
<script>
var trPassArray = $("tr input[id*='RadioButtonPass']").click(function () {
this.closest("tr").setAttribute("bgcolor", "yellowgreen");
console.log("zmien na green");
console.log(closest("tr"));
});
var trFailArray = $("tr input[id*='RadioButtonFail']").click(function() {
this.closest("tr").setAttribute("bgcolor", "orangered");
console.log("zmien na red");
console.log(this.closest("tr"));
});
console.log(trPassArray);
console.log(trFailArray);
</script>
</body>
*.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonSubmitId_Click(object sender, EventArgs e)
{
this.PopulateTable(TableForMethods, value);
ButtonSubmitResults.Visible = true;
}
protected void ButtonSubmitResults_Click(object sender, EventArgs e)
{
}
private void PopulateTable(Table table, string value)
{
string[] sep = { "<br>" };
var words = value.Split(sep, StringSplitOptions.RemoveEmptyEntries);
for (int iterator = 1; iterator <= words.Count(); iterator++)
{
var tRow = new TableRow { ID = "Row" + iterator };
table.Rows.Add(tRow);
var tCell = new TableCell();
var myLabel = new Label
{
Text = words[iterator - 1],
ID = "Label " + iterator
};
var radiobuttonPass = new RadioButton
{
Text = "Pass ",
ID = "RadioButtonPass " + iterator,
GroupName = "passFailGroup" + iterator,
};
radiobuttonPass.CheckedChanged += passRadioButton_CheckedChanged;
var radiobuttonFail = new RadioButton
{
Text = "Fail ",
ID = "RadioButtonFail " + iterator,
GroupName = "passFailGroup" + iterator,
};
radiobuttonFail.CheckedChanged += failRadioButton_CheckedChanged;
var upPassFail = new UpdatePanel { UpdateMode = UpdatePanelUpdateMode.Conditional };
upPassFail.ContentTemplateContainer.Controls.Add(radiobuttonPass);
upPassFail.ContentTemplateContainer.Controls.Add(radiobuttonFail);
var passTrigger = new AsyncPostBackTrigger
{
ControlID = radiobuttonPass.ID,
EventName = "CheckedChanged"
};
upPassFail.Triggers.Add(passTrigger);
var failTrigger = new AsyncPostBackTrigger
{
ControlID = radiobuttonFail.ID,
EventName = "CheckedChanged"
};
upPassFail.Triggers.Add(failTrigger);
var labelComment = new Label
{
Text = " Comment:",
ID = "LabelComment " + iterator.ToString()
};
TextBox textBoxComment = new TextBox { ID = "TextBoxComment " + iterator.ToString() };
tCell.Controls.Add(myLabel);
tCell.Controls.Add(radiobuttonPass);
tCell.Controls.Add(radiobuttonFail);
tCell.Controls.Add(labelComment);
tCell.Controls.Add(textBoxComment);
tRow.Cells.Add(tCell);
}
}
What you're trying to do won't work. ViewState is used by the server application to store information between requests.
During the course of page load or a postback the server modifies the state of the page or its controls
When you post back, without some way to "remember" what was done, all of those changes would be lost. It would be like loading the page for the first time again.
ASP.NET solves this by writing details about the controls in a form field (ViewState.) That way every time there's postback you're sending data back to the server telling it what the state of the page and controls are, so it can recreate it.
You're making changes to the HTML on the client. At that point the page has been rendered, including ViewState. It only keeps track of the server's changes, not anything that happens on the client. So the server will never know that those changes happened.
There are a few ways to solve this (more than two, but these are the obvious ones.)
Whatever changes have to happen to modify that table, do it on the server. If the user interacts with something, do a postback to the server. The server modifies the table, and assuming that ViewState is enabled for the table, those changes are already written to ViewState and persisted.
Avoid postbacks. If there aren't server controls then after the page loads it behaves just like a normal HTML page, and you can do whatever you want on the client.
This gets a little messy: store client-side changes on the client. When you update the table on the client then you could store it in localStorage. When the page refreshes you could then have a client script that checks localStorage and restores whatever client-side stuff you stored there. Think of it as just like ViewState, but the opposite. ViewState stores server-side data between roundtrips. localStorage stores client-side data between roundtrips. The catch is that maybe on some postback you'll completely change the table (like new data, something else) and you'll have to have a way to distinguish that so that in that scenario you don't refresh it from localStorage.
Mixing WebForms with client-side code can be a little frustrating. We start learning about all of these neat client-side tools, but they don't always play well with the behavior of WebForms. Client-side code wants to change things on the page. WebForms wants to refresh the whole page.
Personally I would go with option one or two if possible vs trying to cross-breed the behavior of the two.

Jquery UI dialog with parameters issue

I am trying to pass parameters to Jquery UI dialog for the new page. The new page has Page_Load method which connects to the database and displays the data. I am having issue with Page_Load method getting called first before $(document).ready. So parameter is empty. I appreciate any suggestions.
MainPage.aspx:
function ShowGraph(sId) {
var oid = sId;
$("#dialog")
.load('Graph.aspx')
.data("sId", sId)
$('#dialog').dialog('open');
}
<div id="dialog" title="My Dialog Title">
</div>
Graph.aspx:
$(document).ready(function () {
$get('<%= HiddenId.ClientID %>').value = $("#dialog").data('sId');
});
<asp:HiddenField runat="server" id="HiddenId"></asp:HiddenField>
code behind
protected void Page_Load(object sender, EventArgs e)
{
BL.GetNumbers(HiddenId.Value);
}
Pass parameter in query string like
function ShowGraph(sId) {
var oid = sId;
$("#dialog")
.load('Graph.aspx?sId='+sId)
$('#dialog').dialog('open');
}
and on page load event you can get it.

Getting the messages/notifications instantly without refreshing the page in asp.net

I have a label which I show numbers in and numbers are the count of data from database. Whenever new data is saved in DB, the number in label should increase. It increases when i refresh the page, because I call the method on page_load in codebehind.
What in my mind is that:
I should call the method periodically without refreshing the page.
For this purpose, I know that I should use AJAX, but I couldnt find appropriate usage for me.
Can you direct me to a solution?
This is the label on aspx page:
<div id="panoramCouponBarLittleTalep">
<asp:Label ID="LabelTalepSayisiSag" ClientIDMode="Static" Text="" runat="server" />
</div>
This is the page_load :
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] != null)
{
if (!IsPostBack)
{
SonBesGunTalepSayisi();
}
}
}
And the method I use:
private void SonBesGunTalepSayisi()
{
RequestProvider rP = new RequestProvider();
int talepSayisi = rP.LastFiveDaysRequestCount();
if (talepSayisi > 0)
{
LabelTalepSayisiSag.Text = talepSayisi.ToString();
}
else
{
LabelTalepSayisi.Text = "";
}
}
I would use an ASP.NET AJAX Page Method to be the server endpoint that your JavaScript AJAX will call, based upon a timer; like this:
Code-behind:
[WebMethod]
public static string GetRequestCount()
{
RequestProvider rP = new RequestProvider();
int talepSayisi = rP.LastFiveDaysRequestCount();
if (talepSayisi > 0)
{
return talepSayisi.ToString();
}
return "";
}
I would add a CssClass value to your Label control as that will make it easier to use in a jQuery selector, like this:
Markup:
<div id="panoramCouponBarLittleTalep">
<asp:Label ID="LabelTalepSayisiSag" ClientIDMode="Static"
Text="" runat="server" CssClass="TheLabel" />
</div>
$(document).ready(function() {
setInterval(ajaxCall, 5000); // 5000 MS == 5 seconds
});
function ajaxCall() {
$.ajax({
type: "POST",
url: "PageName.aspx/GetRequestCount",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
// Put result of call into label
$('.TheLabel').text(result);
}
});
}
Note: Obviously you can adjust the timer interval value to be larger or smaller, depending upon your needs and performance. Also, the CssClass value on the Label control avoids the name mangling issue that plagues ASP.NET server controls. Even though you are using the ClientIDMode="Static", I like to avoid using the ID of a server control in jQuery when possible, because a class name will not get mangled by ASP.NET.
You can use ASP Page Methods to do it:
http://www.geekzilla.co.uk/View7B75C93E-C8C9-4576-972B-2C3138DFC671.htm

ASP.Net double-click problem

having a slight problem with an ASP.net page of mine. If a user were to double click on a "submit" button it will write to the database twice (i.e. carry out the 'onclick' method on the imagebutton twice)
How can I make it so that if a user clicks on the imagebutton, just the imagebutton is disabled?
I've tried:
<asp:ImageButton
runat="server"
ID="VerifyStepContinue"
ImageUrl=image src
ToolTip="Go"
TabIndex="98"
CausesValidation="true"
OnClick="methodName"
OnClientClick="this.disabled = true;" />
But this OnClientClick property completely stops the page from being submitted! Any help?
Sorry, yes, I do have Validation controls... hence the icky problem.
Working on this still, up to this point now:
ASP code:
<asp:TextBox ID="hidToken" runat="server" Visible="False" Enabled="False"></asp:TextBox>
...
<asp:ImageButton runat="server" ID="InputStepContinue" Name="InputStepContinue" ImageUrl="imagesrc" ToolTip="Go" TabIndex="98" CausesValidation="true" OnClick="SubmitMethod" OnClientClick="document.getElementById('InputStepContinue').style.visibility='hidden';" />
C# code:
private Random
random = new Random();
protected void Page_Load(object sender, EventArgs e)
{
//Use a Token to make sure it has only been clicked once.
if (Page.IsPostBack)
{
if (double.Parse(hidToken.Text) == ((double)Session["NextToken"]))
{
InputMethod();
}
else
{
// double click
}
}
double next = random.Next();
hidToken.Text = next + "";
Session["NextToken"] = next;
Actually... this nearly works. The double click problem is pretty much fixed (yay!) The image still isn't hidden though.
The general approach is twofold.
Serverside:
On load of the page, generate a token (using System.Random), save it in the session, and write it to a hidden form field
On submit, check that the hidden form field equals the session variable (before setting it again)
Do work
Clientside:
Similar to what you have, but probably just hide the button, and replace it with some text like 'submitting'.
The important thing to note, client side, is that the user may cancel the post by hitting 'escape', so you should consider what to do here (depending on how far along they are the token won't be used, so you'll need to bring the button back from being disabled/hidden).
Complete example follows:
C# (includes code to see it in action):
<html>
<head runat="server">
<title>double-click test</title>
<script language="c#" runat="server">
private Random
random = new Random();
private static int
TEST = 0;
public void Page_Load (object sender, EventArgs ea)
{
SetToken();
}
private void btnTest_Click (object sender, EventArgs ea)
{
if( IsTokenValid() ){
DoWork();
} else {
// double click
ltlResult.Text = "double click!";
}
}
private bool IsTokenValid ()
{
bool result = double.Parse(hidToken.Value) == ((double) Session["NextToken"]);
SetToken();
return result;
}
private void SetToken ()
{
double next = random.Next();
hidToken.Value = next + "";
Session["NextToken"] = next;
}
private void DoWork ()
{
TEST++;
ltlResult.Text = "DoWork(): " + TEST + ".";
}
</script>
</head>
<body>
<script language="javascript">
var last = null;
function f (obj)
{
obj.src = "http://www.gravatar.com/avatar/4659883ec420f39723c3df6ed99971b9?s=32&d=identicon&r=PG";
// Note: Disabling it here produced strange results. More investigation required.
last = obj;
setTimeout("reset()", 1 * 1000);
return true;
}
function reset ()
{
last.src = "http://www.gravatar.com/avatar/495ce8981a5127a9fd24bd72e7e3664a?s=32&d=identicon&r=PG";
last.disabled = "false";
}
</script>
<form id="form1" runat="server">
<asp:HiddenField runat="server" ID="hidToken" />
<asp:ImageButton runat="server" ID="btnTest"
OnClientClick="return f(this);"
ImageUrl="http://www.gravatar.com/avatar/495ce8981a5127a9fd24bd72e7e3664a?s=32&d=identicon&r=PG" OnClick="btnTest_Click" />
<pre>Result: <asp:Literal runat="server" ID="ltlResult" /></pre>
</form>
</body>
</html>
If you have validation on the page, disabling the button client side gets a little tricky. If validation fails, you don't want to disable the button. Here's a snippet that adds the client side event handler:
private void BuildClickOnceButton(WebControl ctl)
{
System.Text.StringBuilder sbValid = new System.Text.StringBuilder();
sbValid.Append("if (typeof(Page_ClientValidate) == 'function') { ");
sbValid.Append("if (Page_ClientValidate() == false) { return false; }} ");
sbValid.Append(ctl.ClientID + ".value = 'Please wait...';");
sbValid.Append(ctl.ClientID + ".disabled = true;");
// GetPostBackEventReference obtains a reference to a client-side script
// function that causes the server to post back to the page.
sbValid.Append(ClientScript.GetPostBackEventReference(ctl, ""));
sbValid.Append(";");
ctl.Attributes.Add("onclick", sbValid.ToString());
}
See this asp.net thread for more info.
Update: the above code would be used to add the OnClientClick handler in code behind. You could also write the javascript in your aspx markup like so:
<script type="text/javascript">
function disableButton(button)
{
// if there are client validators on the page
if (typeof(Page_ClientValidate) == 'function')
{
// if validation failed return false
// this will cancel the click event
if (Page_ClientValidate() == false)
{
return false;
}
}
// change the button text (does not apply to an ImageButton)
//button.value = "Please wait ...";
// disable the button
button.disabled = true;
// fire postback
__doPostBack(button.id, '');
}
</script>
<asp:ImageButton runat="server" ID="VerifyStepContinue" ImageUrl="button.png"
ToolTip="Go" TabIndex="98" CausesValidation="true" OnClick="methodName"
OnClientClick="return disableButton(this);" />
I have solved this by setting a hidden field on the client click before hitting the server.
Then in the server I check the hidden field and if the value is for example something 'FALSE' that might mean I can or cannot of the action.
Similar to Silky's client-side response, I usually make two buttons that look alike except that the second button is disabled and hidden. OnClientClick of the normal button swaps the display styles of the two buttons so that the normal button is hidden and the disabled button is shown.
The double-click feature is a server-side implementation to prevent processing that same request which can be implemented on the client side through JavaScript. The main purpose of the feature is to prevent processing the same request twice. The server-side implementation does this by identifying the repeated request; however, the ideal solution is to prevent this from occurring on the client side.
In the HTML content sent to the client that allows them to submit requests, a small validation JavaScript can be used to check whether the request has already been submitted and if so, prevent the online shopper from submitting the request again. This JavaScript validation function will check the global flag to see if the request has been submitted and, if so; does not resubmit the request. If the double-click feature is disabled on the server, it is highly recommended that the JSP and HTML pages implement this JavaScript prevention.
The following example prevents the form from being submitted more then once by using the onSubmit() action of the form object:
...
<script>
var requestSubmitted = false;
function submitRequest() {
if (!requestSubmitted ) {
requestSubmitted = true;
return true;
}
return false;
}
</script>
...
<FORM method="POST" action="Logon" onSubmit="javascript:submitRequest()">
......
</FORM>
for those who just want to do a quick fix , just hide it and show another button that has no events
<asp:Button ID="RedeemSubmitButton" runat="server" Text="Submit to Redeem" OnClick="RedeemSubmitButton_Click" OnClientClick="hideit();" />
<asp:Button ID="RedeemSubmitButtonDisabled" style="display:none;" runat="server" Text="please wait" OnClientClick="javascript:alert('please wait, processing');" />
<script>
function hideit() {
var btn = $get('<%= this.RedeemSubmitButton.ClientID %>');
var btn2 = $get('<%= this.RedeemSubmitButtonDisabled.ClientID %>');
if (btn != null)
{
btn.style.display = 'none';
btn2.style.display = 'block'
}
}
</script>

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