I have a button that has click event in my C#. This works great. However afetr pressing F5 to refresh the page I noticed the button event is fired. This occurs every time I click F5. I've added if(page.IsPostBack) and the method still runs.
Is there any way to stop this method from firing when the F5 Refresh button is clicked?
Thanks!
http://pastebin.com/9ycNraaT
try to use Response.Redirect("Your page ") after the your add/update code. it isn't good practice, but it will help you.
if(!page.IsPostBack)
NOT if(page.IsPostBack)
If you have a page that needs to be run once, you should implement logic in your code that prevents the same method from running multiple times. In pseudo-code:
if (canExecuteMethod()) {
executeMethod();
} else {
displayMessageThatMethodCannotBeExecuted();
}
For example, you can check a Session variable with canExecuteMethod(), which returns false when it is not present and is set in executeMethod():
function canExecuteMethod() {
return Session["methodIsExecuting"] == null
|| Session["methodIsExecuting"] == false;
}
function executeMethod() {
Session["methodIsExecuting"] = true;
// ...
}
Of course the use of a Session variable has it limits, so you might want to consider using a database or AppSettings variable instead.
No way. If once you click button (and post data) after refresh the same data will be sended.
Related
I have a grid that is populated on Page_Load. The first time showing user data from the database excluding deleted items (I have a field in the database called RecordIsDeletedYN which if set true means the record is deleted). So my Page_Load code looks like this:
if(Session["ShowDeletedItems"] != null)
ShowDeletedItems = Convert.ToBoolean(Session["ShowDeletedItems"]);
else
ShowDeletedItems = false;
PopulateGrid();
I have a page variable declared at the top of the form:
private bool ShowDeletedItems = false;
My thinking is that the first time the page is loaded the above code sets the page variable to false.
Then the Page_Load calls my PopulateGrid function. In there I have an SQL query that is constructed based on the value of the ShowDeletedItems bool variable.
If ShowDeletedItems is false then a WHERE statement is included in the SQL Query that adds:
strSQL += "WHERE (RecordIsDeletedYN = 0) ";
So on start up ShowDeletedItems is false so the SQL WHERE is included and we don't show Deleted Items in the grid! This works!
Also on my screen is a button that when pressed looks at the state of the page Variable if it's false then it flips it to true and if its false it flips it to false. This is the code:
protected void imgButtShowDeleted_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
if(ShowDeletedItems)
Session["ShowDeletedItems"] = "False";
else
Session["ShowDeletedItems"] = "True";
}
This setup works but ONLY after the button is pressed a second time and thereafter it works perfectly on each subsequent press.
Where am I going wrong. I know it must be something to do with the way page events fire. I tried initialising the Session variable in Page_Init to false but when I did that it never shows the deleted items. The session variable is always set false.
Any help appreciated with this.
You set ShowDeletedItems in the Page.Load event handler. According to ASP.NET Page Life Cycle, the Load stage occurs before the Event handling stage. So, the Page.Load event is raised before any Control-changed event.
In your case, the Page_Load handler is called before the imgButtShowDeleted_Click handler. Therefore you see the updated data only after additional postback after clicking the button.
To solve this issue, re-bind the grid after you changed the ShowDeletedItems variable in the imgButtShowDeleted_Click event handler.
Avoid the page level var for confusion...have a get/set property on the page that directly gets or sets your session var...it'll simplify your code and make it less likely to have such problems.
Also consider if it's page only and doesn't require rentention across new page requests...consider using viewstate instead of session.
I have custom validators on the aspx page and user needs to see the error message in summary as soon as they tab out of the control.
To achieve this, I am calling Page_ClientValidate('') on onblur event of each control. One of the custom validator I have is:
function ValidateCustomerId(oSrc, args) {
var txtCustomerId = document.getElementById(txtCustomerId);
if (txtCustomerId != null) {
var customerId = txtCustomerId.value;
if (!isInteger(customerId)) {
document.getElementById("customerIdAsterik").style.display = 'inline';
args.IsValid = false;
}
else {
document.getElementById("customerIdAsterik").style.display = 'none';
}
}
}
If user enters invalid entry and clicks on Cancel button, server side event is not getting fired untill it is clicked twice. Cancel button already has CausesValidation=false. I think this behaviour is due to calling on Page_ClientValidate() on onblur event, otherwise it works fine.
Is there to skip the client validations when they click on cancel button or is there any approach I could take to achieve this.
Similar kind of issue is listed here:
http://weblogs.asp.net/gurusarkar/archive/2013/05/30/after-first-postback-why-i-have-to-click-the-button-twice-for-postback-to-occur.aspx
Not sure if that applies but the Validation is fired due to the onblur.
So I think setting that Page_Block=false in the button click might work.
I am a new C# user and now I have encountered a problem in using BindingNavigator.
I am using bindingNavigator to update records in a table of database. Before I leave current updated record and enter the next record by clicking Next button, I will perform some validation, if there is any thing incorrect, I hope it could raise a warning to give me chance to correct the wrong fields instead of moving to the next record.
I added some lines in bindingNavigatorMoveNextItem_MouseDown event, but it still move to next item even there are some thing wrong with current record(fields have some logical connection). Can any expert here help me out about that? Many Thanks!
You have two approaches: either overriding WndProc and prevent mouse click window message from calling the base's WndProc, or simply overriding OnMouseClick:
class Hello : BindingNavigator
{
private bool canFire = false;
protected override void OnMouseClick(MouseEventArgs e) // second approach
{
// don't call base method so that event doesn't fire up
if (this.canFire)
base.OnMouseClick(e);
}
}
I know this is old.. but for anyone else...
You should use the normal buttons, and just use the validating event, canceling if anything fails your validation.
The control does not display the property in the designer, but you can still set it : bindingnavigator.CausesValidation = true;
I do this in the form load.
this alone still won't do it.
you also need to set the focus.
bindingnavigator.focus();
I do this in the bindingnavigator_ItemClicked event so it happens no matter what button is clicked.
I have a requirement to check for a certain condition on postback before redirecting (Response.Redirect) to another page.
Note... I cannot use JavaScript to detect whether or not to confirm (this is also a requirement) :s
Pseudo:
protected void lbtnRedirect_OnClick(object sender, EventArgs e)
{
if (showConfirm)
{
// Set flag for client side
this.ShowConfirm = true;
// Track this event for next postback.
}
else
{
Response.Redirect("somepage.aspx");
}
}
If the showConfrim flag == true, then the client will be show a modal dialog box asking them if they are sure they want to redirect. If the user clicks on "Yes", then the page posts back and the desired effect is that the lbtnRedirect_OnClick event is fired. How would I about tracking the lbtnRedirect event?
Edit:
I have no problem tracking the flag to show the modal (yes JS must be used to show the modal... somethings you just cannot get rid of :)). I should have been more clear.
It is when the user clicks "Yes" to continue the redirect. The page will postback again but needs to know which event to go through.
i.e. Suppose there are 3 onclick events, 1) lbtnRedirect1_Onclick 2) lbtnRedirect2_OnClick 3) lbtnRedirect3_OnClick... each of which does the confirm check.
Each onclick event does the check. So when the user clicks on "Yes" on the modal, how does the page know which event to drop back into?
You can use ViewState if you're in WebForms.
Implement a ShowConfirm property encapsulating ViewState["ShowConfirm"].
In the first postback you'll set ShowConfirm 'true', and this will activate that modal during the render (if ShowConfirm is true, that's setting as visible 'true' some control).
In the next postback, you'll set ShowConfirm 'false' because is 'true', and finally you'll do the whole redirect!
You can use an ajax call from javascript to set the required values.
Since the postback will happen before even the execution reaches to your button click event we need a workaround here, And if you don't need JS as your requirement, so take a look at
Implementing Client Callbacks Programmatically without Postbacks in ASP.NET
This is much like a wrapper for XMLHttp Ajax call IMHO.
You cannot easily create a model form, without javascipt.
One suggestion I would make is to have panels in your page.
Panel one is visible.
On submit one; panel one hides and panel two is visible asking for a confirmation.
On panel two is a confirm button, clicking this button your redirection is performed.
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/