I have created a user control to handle adding comments to certain business entities, like contacts and customers. Works great ... except for one issue.
I am using a ListView control to edit and delete comments, and a separate area, on the same user control to add a new comment. All of this is wrapped in an UpdatePanel.
Here is my scenario ... the user adds a new comment ... the page does a postback, the data is successfully saved, and the ListView control is updated to show the new comment. Now, if the user refreshes the browser, it will naturally postback again and will add another duplicate record.
Any ideas on how best to prevent this?
You could try using the Post/Redirect/Get pattern. Basically instead of letting the postback send the data, redirect to the page. That way, if a user refreshes, s/he is refreshing the GET command rather than the POST.
Sorry.. missed the UpdatePanel piece. Make sure that your submit button is also within that UpdatePanel. A page refresh would not affect your AJAX call, but when the button is outside the panel, it's doing a regular postback so you would be sending the Add Request again.
I haven't used ASP.NET in a few years, but you should wrap your "do this on postback" code in Page.IsPostBack:
if(IsPostBack) {
//do your data-saving code...
}
MSDN link
Related
I have the following scenario:
UserControlA contains a <asp:Button id="bSomeid" onClick="AddItem" /> with some code to an item to a shopping basket in AddItem.
UserControlB contains some LinkButton's that dynamically add a selection of UserControlA to the page in the OnClick event.
This is all done in an UpdatePanel. It is a little more complicated but I have pruned the information to what I believe is causing the problem, I will add more information if necessary.
The problem I have is that it takes 2 clicks for the AddItem event to trigger after I have added the items to the page after clicking the LinkButton.
I understand why this is happening - it is to late in the page cycle to register events for the next post back in the onclick - but can anyone think of a way around this? Can I force an event to be triggered on the next postback? I have tried to think of a way to run my code in page_load but I requuire access to the sender in the onClick.
Using .NET 4.0.
EDIT
I managed to find a way to get the link button sending the request in the Page_Load (using Request.Form["__EVENTTARGET"];) so I moved my code to the Page_load event. It still requires 2 clicks so I am assuming it isn't something to do with the onClick being registered to late.
Are there any other general things to check that could cause a button to require 2 clicks to post an event properly?
If your suspicion about being late in page life cycle is true then you can try using ScriptManager.RegisterAsyncPostBackControl method to register dynamically added controls in the link button click - considering that your button is within user control, you need to add public method into UserControlA that would actually register the button bSomeid1 and link button click from UserControlB would actually call the A control's method.
EDIT :
Another cause for button click not happening can be that button being dynamic control is not added in the page hierarchy when post-back happens (or it gets added very late in the page life cycle when the post back data is already processed). A really full-proof solution should add dynamic controls back to the page hierarchy in page_load it-self (and strictly maintaining same controls ids within hierarchy). If that's not possible then you can sniff the request (Request.Form) to detect the post-back.
In your case, you should ascertain if the button is indeed causing the post-back on each click. If yes, what is the POST data (Request.Form) for the first request - what is the __EVENTTARGET value on the first click (and post-back)? That should start your trouble-shooting.
On the other hand, a simple work-around could be to use html anchor element (you can still use link button) and have a javascript handler in the click event that would set some hidden variable and then submit the form (you can simulate the click on hidden button to trigger ASP.NET client side submit pipeline) . Now the hidden variable value can be used on the post-back to determine which link button has been clicked.
"Are there any other general things to check that could cause a button to require 2 clicks to post an event properly?"
Does it require two clicks on the control, or does it take accept a single click elsewhere on the screen, and then fire first time with a single click on the control?
I have my own (similar) issue with the Updatepanel where the first (expected) trigger does not fire and it seems that a single click elsewhere, and then the subsequent triggers fires first time (which totals 2 clicks)
[edit] Since you are working on this ATM, it may help me as well. Do you have a textbox with a trigger event on it? I do, and if I leave this blank (so that it does not fire) then there is no need for a second click.
I have an ASP.NET web form on which I'm displaying a list of database items via user controls, generating the user controls dynamically - working fine.
Also on the page, I have an asp:dropdownlist filled with items that can be added to this database list. Along with this dropdown I have a button 'ADD'. My intent is that the user chooses and item, clicks add, and then the list of user controls on the form will include this new item.
I have all this working.
My issue is that the user control has a button 'DELETE', which removes the selected item from the list. That works, EXCEPT when I add a new item. Because my 'add' button event is always fired after Page_Load, even if I regenerate the list of user controls, the internal user control click events won't fire because the controls weren't created as part of Page_Load.
I need to know what I'm doing wrong, or best practices here, any advice. I tried to be precise in the description of the problem, but if I've not succeeded, let me know and I can add more details.
SIMPLE RESTATE: I need to know how to add a dynamically created user control to a page via a page button click event, and still have the user control internal click(etc) events firing.
Thanks for any help.
EDIT: Based on the feedback from the gentlemen here, and doing some further research related to their suggestions, I ended up implementing a solution based on what's presented on this page:
http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx
Here's a snippet showing how I dealt with this. This snippet resides in my PreInit event handler. Not exactly an elegant weapon for a civilized age, but sometimes a blaster is all you've got to use.
'Look to see if button for adding a new client number has been
'clicked. If so, call the sub to add the item NOW, so that it
'is able to have it's internal click events fire.
For Each control_string As String In Request.Form
Dim ctl As Control = Page.FindControl(control_string)
If (ctl IsNot Nothing) AndAlso (ctl.ID = "cmdAddClientNumber") Then
Me.AddClientNumberToList()
Exit For
End If
Next
On the button handler, you initially add the UserControl to the Page. OnPreInit (which will next be fired when the user clicks Delete on the UserControl), you should re-add the UserControl - so that it exists, and can handle the Delete button event.
You will need to devise your own state tracking mechanism to determine that you need to add the UserControl during PreInit. I generally use ViewState, as evidenced by this seemingly similar post.
Similar question:
How to create and use custom control with UpdatePanel added to the page programmatically
Dynamic control should be re-added to the control tree OnPreInit, see documentation:
PreInit - Create or re-create dynamic controls.
ASP.NET Page Life Cycle Overview
When the ASP.net Page is Postback the controls inside the table is disappear,
but when i click on button that has that code which cause transfer to the page:
Server.Transfer("~/Admins/EditUsers.aspx");
all controls appear easy with no problems.
Then,is there is need to make refresh to the page, or what can i do?
Thanks
A postback already performs a page refresh automatically.
If controls are disappearing, that suggests that you might not be creating them on the postback. Note that tables do not store their contents in ViewState. Is there any chance you are testing for IsPostBack in your page Load handler? If so, you must recreate the table on every load, whether a postback or not.
Beyond that, you'd probably need to provide a bit more specific information.
I have an aspx page that is wrapped with an UpdatePanel control, users can post comments and delete them later, when the user clicks the delete for the first time it deletes successfully but if he wants to delete another comment, it works only after two clicks on the button.
the delete button is inside a web user control that is added dynamically at run time.
Any ideas?
Thanks.
I had a bit different problem. The control event did not work at all after AJAX post back. Here is the possible solution to your problem - http://sharepointtechie.blogspot.com/2011/04/click-event-stopped-firing-after-ajax.html
Please register that control during page load event of the control..
So if you are calling usercontrol1 dynamically during the runtime..
then on the page load event of usercontrol.ascx you should have
this.id="xyz";
try this... It did some miracle for us...
Hope this works for you too
Ok, this is a bit different scenario. I guess I would have to think about doing it this way sort of with MVC anyway if we were actually using MVC...but we're not at the moment.
So I've got and .aspx page. In that .aspx page is a user control (.ascx). And in that user control is a custom control (.cs).
The custom control has a repeater in it. So I'm showing a list of items on that .aspx through the .ascx's custom control. For each item in the repeater is a button. It's just a hyperlink, just a regular on my page
When you click that button, it redirects to whatever page you're on. Since the custom control never knows what your parent .aspx page is, I'm doing a redirect to the self .aspx by doing a Response.Redirect(Request.Path). So that way it always redirects to whatever .aspx is using that user control and custom control.
So after it redirects to self, I check the querystring in the page_load of whatever .aspx is using it. If the value is true, then I handle it however the .aspx wants to. In this case when it's true, I call a method in the code behind of my .aspx that handles the action for the button. For example lets say that button was "Add to Shopping Cart", the .aspx handles that action and calls a AddToCart method in the .aspx.cs.
I'm not using an ASP.NET control for the actual hyperlink and button because I just don't need it and in my particular case I'm using a user control and a custom server control. For this instance, I had some issue where I didn't wnat to use an ASP.NET control...I forget why but the point is, no this is what it is.
So with that, I'm trying to figure out how I can apply some AJAX here call to call that method instead. I still need to somehow redirect again back to the same page like I'm doing...I'm doing the redirect in that method after all the logic at the end. I am redirecting again back to the same page, because I need my Page_Load methods in my .aspx and also in an .ascx to still fire off after that method is completed.
So I am not sure where to start on this. Let me go through this once again:
Custom control has a repeater in it and in the repeater, each item has a standard HTML hyperlink (non ASP.NET control) which wraps a standard image tag (image is a button)
User control contains the custom control
The .aspx page contains the user control
User clicks the button and hyperlink redirects them to the parent .aspx page that is using this custom control...so it calls Response.Redirect(Request.Path)
In the code-behind of this .aspx, in my page_load I check a querystring flag to see if I performed that action..meaning user clicked that button. For example one of the querystring params is "AddItem" and another querystring param is "itemID". If movedItem is true, then I fire off a method called MoveItem(int itemID)
Method MoveItem is called
Method MoveItem redirects again back to this same .aspx using Response.Redirect(Request.Path).. this is so that the page load is hit again as well as my .ascx page load is hit. Because in both those page loads, I rebind a repeater so I can show the latest state of the lists. I call a method in my .aspx page_load which rebinds a grid and then page_load in my .ascx also calls another method which rebinds some other list
You can use $.get() to pass the variables to a server-side method that performs any server-side functions you need. You don't need to run page_load or have a code behind.
If you only need to update the HTML in the client's browser then you can use jQuery to add/remove them from the lists in the HTML. You can use the html() function in jQuery to append the item to the list.
You should look at DataTables.net as you can build a client side, editable grid that will perform Ajax updates as well. You would be able to keep your repeater control, but eliminate all the back and forth to the server and the deciphering of clicks and coordinating between Page_Load and etc. Here is a good post from Dave Ward(Encosia) that covers jQuery, Page_Methods and repeater controls.
If you want to preserve your work so far, why not try Ajax Update Panels around the region that you do not want to visible "refresh"?
Remember that the first A of AJAX is asynchronous. You'll want to avoid having your button reload the page, of course. Something like:
Figure out the data you need to send to your "add to shopping cart" handler page -- part number (SKU, etc.), colors, sizes, quantity, etc.
Ensure this data is on every applicable page, in an identical fashion: perhaps one or more hidden input elements, or even from the page URL.
Replace the custom control hyperlink/button href with a [client side] onclick handler instead, which will get the data from step 2 and send it via $.ajax() (or $.post or $.get), specifying the response handlers. You probably want to disable the button or give other visual feedback to avoid duplicate clicks.
In the response handlers, update the shopping cart section of the page with the number of items or indicate success or failure.