Dynamically Adding AsyncPostBack Triggers - c#

In the Page_Load section of my code I am dynamically creating a form. Each row has a save button at the end and I want the form to asynchronously post back when someone clicks the "save" button at the end of a row. I can't seem to achieve this though. I click the button and nothing happens. The click event is not even firing so my guess is that the trigger is not being added properly. Any ideas how I can get this functionality working?
Here is a snippet of my code that I believe is where the problem lies.
Button submit = new Button();
submit.ID = "Submit_" + reader["SEQN"];
submit.Text = "Save";
submit.Click += submitTest;
AsyncPostBackTrigger apt = new AsyncPostBackTrigger();
apt.ControlID = submit.UniqueID;
UpdatePanel1.Triggers.Add(apt);

A couple things i see. Set the trigger Event to the event you want executed: apt.EventName = . The second thing is the id of the button correct after final page rendering. Check the Buttons id value from web inspector or firebug and see if its the same as what you set for controlid.

Related

C# ASP.net How to add a reload of the page/panel at the end of a button event?

I have a page that consists of an updatepanel with a DropDownList, a textbox and a button in it. The updatepanel has a trigger for the button. This works fine for all my "error" cases, such as "No input!", when I pop an alert with
ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(),"noName", "window.onload = function(){alert('Please enter a username!');window.location ='Accounts.aspx';}", true); and the like.
But when I don't hit the alerts and the button event runs all it should I seem to land in some dead zone. My alerts stop displaying even though the code runs (checked by debugging), the button event does still preform all tasks as it should. However, if I refresh the page I get the classic:
To display webpage again. After I click retry my "latest" message pops up and then it works just like on first load.
So, I'm guessing that the PostBackTrigger on my button triggers a PostBack before or during the event execution since when the event is done nothing more happens until I reload. I'm thinking I need to add a reload at the end of my button event. Therefore my question is: How do I add a reload of the page/panel at the end of a button event?
Edit:
Forgot to mention that when the button event runs all it should it edits the web.config file, if this somehow could cause my issue.
I found a solution to my problem, by removing my triggers and instead using:
ScriptManager1.RegisterPostBackControl(Button);
Then I could also put an:
UpdatePanel1.Update();
At the end of my button event.

Selenium Wait doesn't wait for Element to be Clickable

I have a page that is dynamically loaded and contains a button. I am trying to wait for the button to be available to be clicked with selenium using the C# bindings. I have the following code:
WebDriverWait wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(30));
wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("addInspectionButton")));
var button = Driver.Instance.FindElement(By.Id("addInspectionButton"));
button.Click();
this doesn't work though. The click event is never fired. The selenium script doesn't throw an exception alerting that the element with an ID of "addInspectionButton" doesn't exist. It just isn't able to click it. If i add a Thread.Sleep(3000) Between the wait statement and the line where I get a handle on the button element it works.
Am i not using the ExpectedConditions.ElementToBeClickable correctly here?
It turns out that an event was being bound to the button after the button was dynamically added to the page. So the button WAS being clicked but nothing was happening. The sleep thread being placed in the code was just giving the client side event time to be bound.
My solution was to click the button, check for the expected result, and then repeat if the expected result wasn't in the DOM yet.
Since the expected result was for a form to open I polled the DOM like this:
button.Click();//click button to make form open
var forms = Driver.Instance.FindElements(By.Id("inspectionDetailsForm"));//query the DOM for the form
var times = 0;//keep tabs on how many times button has been clicked
while(forms.Count < 1 && times < 100)//if the form hasn't loaded yet reclick the button and check for the form in the DOM, only try 100 times
{
button.Click();//reclick the button
forms = Driver.Instance.FindElements(By.Id("inspectionDetailsForm"));//requery the DOM for the form
times++;// keep track of times clicked
}

Not able to call event handler on new control added to update panel after first asynchronous call back

So I am not able to call an event on an update panel after the first postback. The event is assigned to the control on postback, but doesn't work. The code below is what happens in the control added after postback.
//Add Delete Control
up.ContentTemplateContainer.Controls.Add(new LiteralControl("<div class=\"news_delete\">"));
LinkButton deleteLink = new LinkButton();
deleteLink.ID = item.ID.ToString();
deleteLink.Text = "Delete This News Item";
deleteLink.Click += new EventHandler(DeleteNewsItem);
up.ContentTemplateContainer.Controls.Add(deleteLink);
up.ContentTemplateContainer.Controls.Add(new LiteralControl("</div>"));
The control gets added to the update panel and I can see it, but when I click on the link button it doesn't run the event DeleteNewsItem. The event can be seen below.
//OnSubmits
void DeleteNewsItem(object sender, EventArgs e)
{
SPList newsList;
SPWeb web = SPContext.Current.Web;
web.AllowUnsafeUpdates = true;
web.Update();
newsList = web.Lists["News Wire"];
SPListItemCollection items;
items = newsList.Items;
LinkButton item2Delete = (LinkButton)sender;
SPListItem item = items.GetItemById(Int32.Parse(item2Delete.ID));
item.Delete();
newsList.Update();
web.AllowUnsafeUpdates = false;
System.Web.HttpContext.Current.Response.Redirect(SPContext.Current.Web.Url);
}
So once again i would like reiterate that it works before I do a postback on the update panel. What I mean is the first set of items that have this delete control work and delete the list item, but when I do the asynchronous postback it doesn't ever run the event when I click on it. I have set breakpoints and it never reaches it(the event). I wonder if this has to do with the web part lifecycle or the page lifecycle. Please someone help. By the way this is not a visual webpart, but it is a webpart.
This is indeed a lifecycle issue. Take a look at the following post, which will explain your problem and a possible workaround : ASP.Net Dynamically populate controls on postback
The following post can also give a workaround for the problem.

Moving button stops click event happening

I have a button, contained in a panel, with a click event, that works fine. However when a users presses another button, I need to move this button into another panel (this is actually a panel with a modalpopupextender), so I this code to do so:
newPanel.Controls.Add(buttonPanel)
It all get's moved and looks fine. However now when the button is clicked it doesn't fire the associated event. I have tried re-adding the event in the page_init, with this code
((Button)this.FindControl("serverModalSave")).Command += new CommandEventHandler(modalSave_Click);
But with no luck. How can I get this button to fire it's click event when moved, and why does it stop working when it's moved?
EDIT:
This Button needs to be added to a panel specified by the user at run time, so there is not a way to determine where the button will go in advance.
I could instead of moving this button, create a new one, but because this button is not created in the page_init I am having issues getting that to fire an event either.
Instead of moving the button, have another button on the other panel set to hidden.
Hide the button you wanted to move and show the hidden one when needed.
Moving the control changes the naming hierarchy and now the button can't be found and the click event can't fire.
This is due to how the page life cycle works. Here is a good (if somewhat dated) article about how view state works - if you understand this, you will understand what went wrong.
If you are creating the button in the new panel, when this button is then clicked do you re-create it in the postback ?
You must re-create all controls on each postback see here

ASP .NET Button event handlers do not fire on the first click, but on the second click after a PostBack

Background: I am customizing an existing ASP .NET / C# application. It has it's own little "framework" and conventions for developers to follow when extending/customizing its functionality. I am currently extending some of it's administrative functionality, to which the framework provides a contract to enforce implementation of the GetAdministrationInterface() method, which returns System.Web.UI.Control. This method is called during the Page_Load() method of the page hosting the GUI interface.
Problem: I have three buttons in my GUI, each of which have been assigned an Event Handler. My administration GUI loads up perfectly fine, but clicking any of the buttons doesn't do what I expect them to do. However, when I click them a second time, the buttons work.
I placed breakpoints at the beginning of each event handler method and stepped through my code. On the first click, none of the event handlers were triggered. On the second click, they fired.
Any ideas?
Example of Button Definition (within GetAdministrationInterface)
public override Control GetAdministrationInterface()
{
// more code...
Button btn = new Button();
btn.Text = "Click Me!";
btn.Click += new EventHandler(Btn_Click);
// more code...
}
Example of Event Handler Method Definition
void Btn_Click(object sender, EventArgs e)
{
// Do Something
}
Page_Load Method that calls GetAdministrationInterface
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsAsync)
{
List<AdministrationInterface> interfaces = <DATABASE CALL>;
foreach(AdministrationInteface ai in interfaces)
{
placeholderDiv.Controls.Add(ai.GetAdministrationInterface());
}
}
}
Good grief! I knew it was going to be something this stupid. Purely my fault of course and my lack of knowledge in ASP .NET.
After doing a multitude of Google searches and eventually being blocked by Google on suspicion of being a bot running automated scripts, I managed to squeeze in one last search in and stumbled across this article. Already at the point of giving up, I tried my best to read the article without skipping 10 lines at a time or looking for pretty pictures. In the section titled Assigning IDs to Dynamically Created Controls, I read these magical and most joyful words:
If you view the source HTML before you click the not-working button and after you have clicked it, you will notice a small difference. The buttons have different HTML IDs before and after the post-back. I got ctl04 and ctl05 before the post-back and ctl02 and ctl03 after the post-back.
ASP.NET button recognizes events by checking for a value for its ID in the Request.Form collection. (In truth it happens differently and controls do not check Request.Form collection by themselves. Page passes post data to controls by their IDs and to controls that are registered to be notified about post data). ASP.NET does not fire the Click event, because the button's ID has changed between the post-backs. The button you have clicked and the button you see after are different buttons for ASP.NET.
Sure enough, when I viewed the HTML the first time, my button had the ID ctl04$ctl36. After clicking the button, my button had the ID ctl04$ctl33.
So there you have it! All I had to do was set the ID on the buttons and presto! My event handlers are now being called!
Sample Solution:
public override Control GetAdministrationInterface()
{
// more code...
Button btn = new Button();
btn.Text = "Click Me!";
// !!THE BANE OF MY EXISTENCE!!
btn.ID = "The_Bane_of_My_Existence";
// !!THE BANE OF MY EXISTENCE!!
btn.Click += new EventHandler(Btn_Click);
// more code...
}
What a great way to spend two days...
I had the same problem, but the accepted answer here was not causing it. I had a text box and a search button, and clicking the button the first time didn't perform the search. The event handler of the button wasn't being hit. But clicking the button a second time did trigger the event on the server. Here is why:
If you have an <asp:Textbox> with its AutoPostBack set to true, after typing in the text box and then moving to click a button, the text box causes a post-back immediately the moment it loses focus. So the click even of the button doesn't count (the page is already posted-back as a result of the text box's event). That's why when you click the button a second time, it works because the text box is not involved in the second post-back.
Set the AutoPostBackproperty of the <asp:Textbox> to false to fix this issue.
A quick fix is to set an ID to the ASCX control your are loading on a page. For example, if your code is like this:
UserControl SpecsControl = (UserControl)Page.LoadControl("../name.ascx");
SpecsContainer.Controls.Add(SpecsControl);
then you need to add a line (before Controls.Add):
SpecsControl.ID = "Aribtrary_Name";
Then your handler method is fired at the first click.
I was facing the same problem. My button froze after my first click. For me this annoying problem got solved when I disabled the button's EnableViewState attribute.
For me it was the UpdatePanel , my Button and my TextBox were both inside an UpdatePanel , so when I post-back , it caused some weird behavior . It took it outside of the UpdatePanel and that fixed it .
Even i had the same problem. the cause was "localhost:1656/secure/login.aspx?ReturnUrl=%2f".
if the request contain %2f as query string, the first post will not be succeeded even though "%2f" is representing "/".
one way to avoid this by having a condition check in pageload
protected void Page_Load(object sender, EventArgs e)
{
string queryString = Request.QueryString.ToString();
if(queryString == "ReturnUrl=%2f")
{
Response.Redirect("/secure/login.aspx");
}
}
Whilst its hard to know exactly without seeing the full Page_load method it does smell a little bit like the event handlers are not hooking up until the page is reloaded.
eg:
if (IsPostBack) {
// Add handlers here ...
}
I had same problem. And I searched on internet i didnt find a solution. After that i found sample code and I used it. It worked for me. Web site link is below:
http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/calling-an-Asp-Net-C-Sharp-method-web-method-using-javascript/

Categories