I'm using DevExpress ASPxButton, and I was wondering how can I prevent the user from clicking the button more then once?
Basically it does an update/insert statement.
This can be done using the following code:
var buttonClicked = false;
function MyBtnClick(s,e){
if(buttonClicked) return;
buttonClicked = true;
// do something
}
<ASPxButton id="btn" runat="server">
<ClientSideEvents Click="function(s,e) { MyBtnClick(s,e); } "/>
</ASPxButton>
On the client side, you can disable it when it's clicked.
On the server side, my favourite approach is generally to send a nonce with the form data, and then reject duplicate nonces.
As always, client side validates in a fast and (hopefully) friendly way, server side validates for sure even if client side code suffers from some unexpected browser issue, or someone is deliberately messing things up.
Not sure about aspxbutton specifically but in general you will have something like this on the onclick attribute of the control.
onclick="this.disabled=true;"
In the code where you run the update query simply add to the start of the code:
ButtonNameOrID.Enabled = False // add ; to end if C#
Then at the end of the code, add:
ButtonNameOrID.Enabled = True // add ; to end if C#
This is will disable/enable the button from your C# or VB code.
Related
I want to use a javascript function inside a c# function
protected void button1_Click(object sender,EventArgs e){
//javascript function call ex.
/*
boolean b=the return of:
<script type="text/javascript">
function update() {
var result = confirm("Do you want to delimit the record?")
if (result) {return true;}
else {
return false;
}
}
</script>
*/
}
how can i do such a thing? i want when user press yes return true and i know he pressed yes...can i do so?
If you're trying to add JavaScript to your page from asp.net, you can use the ClientScript class.
string script = "function update() { var result = confirm(\"Do you want to delimit the record?\") if (result) {return true; } else { return false; } }";
ClientScript.RegisterClientScriptBlock(this.GetType(), "someKey", script, false);
If you're trying to call (client side) JavaScript functions from your asp.net code behind, then absolutely not. When the page posts and your C# is run, any JavaScript that was on the page no longer exists.
You're mixing two different technologies. C# runs on the server. It renders an HTML page (which may include Javascript). This page is then sent to a client's browser, where Javascript finally gets executed.
In Javascript you can prompt user about record deletion or whatever, and then you have to either navigate to another page or use AJAX to send result to the server.
I suggest that you get a good ASP.NET book. It will clear many uncertainties for you.
If you're putting this message on an <asp:Button> with postback just add the confirm dialog to the OnClientClick attribute like so:
<asp:Button ID="Button1" runat="server"
OnClientClick="return confirm('Do you want to delimit the record?');" />
If you're simply trying to create the functionality of letting the server know that a button was clicked, you're over complicating things. If you really need to dynamically insert Javascript then what Adam mentioned is worth looking into. But I highly doubt that this is the correct approach for what you're trying to do.
You should really only dynamically insert Javascript when you're worried about performance AND you have a lot of content to send.
If dynamically inserting Javascript (ie. lazy loading) is not your main concern, then here is a very simple example of what most folks would usually do to achieve the functionality you're aiming for.
I know this is a basic question, but I am curious as to what the different options are, and what the best practice would be.
If I have a form that is responsible for saving reservations into a system, how can I prevent the form from being posted twice if the user hits the button twice really quickly?
I know there are a few ways in which I can accomplish this, but I am not quite sure which is the standard way of preventing this. Partially because I am new to web forms, and am used to dealing with MVC.
Thanks ahead of time.
I've used two approaches to this problem:
Use a token based approach. Each page has a hidden input with the current random token. This token is also stored in the user's session. Once the postback occurrs, I compare tokens and, if they are valid, generate a new session token and continue processing. When the second postback occurs, the token no longer matches and prevents processing.
Use javascript to disable the submit button. If you take this approach, and need the button event handler to fire, you'll need to create a hidden input with the name attribute of the button before submitting. The hidden input is required because disabled inputs do not end up in the post data.
I would recommend a client-side onClick event handler that disables the button or makes it invisible, preferably the latter, and replace the button with a label that reads "Processing..." or something like this
I have been using something like this when using an asp:Button for submitting:
1) Set the submit button's UseSubmitBehavior="false"
2) Set the submit button's OnClientClick="pleaseWait(this, 'Please Wait...');"
3) Include javascript code in the page:
function pleaseWait(obj, message) {
if (typeof(Page_ClientValidate) == 'function') {
if (Page_ClientValidate()) {
obj.disabled = true;
obj.value = message;
return true;
}
}
return false;
}
This solution is nice because it is simple but still accounts for client-side javascript validations. It isn't perfect, because it still relies on Javascript, which could be turned off, but that's unlikely to be done by someone who doesn't have the sense to click once and wait for a response. :)
Easy way - use the ajax AnimationExtender control.http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/Animation/Animation.aspx
Simply attach the extender to the button and add a disable action.
<asp:Button ID="CopyScenarioButton" ClientIDMode="Static" OnClick="CopyScenarioButton_Click"
OnClientClick="setTimeout( function() {$('#CopyScenarioButton').attr('disabled', 'disabled');},0)"
EnableViewState="false" Text="Save New Scenario" ToolTip="Save New Scenario"
CssClass="btnNormal" runat="server" />
or the later version that includes some validation first:
function PreSaveHybrid() {
var doSave = PreSave();
if (doSave !== false) //returns nothing if it's not a cancel
setTimeout(function () { $('#btnSave').attr('disabled', 'disabled'); }, 0);
return doSave;
}
How to set in ASP.NET for ImageButton to change picture on mouse hover?
<asp:ImageButton onmouseover="changePic(this);" ...
JavaScript:
function changePic(obj)
{
obj.src = "<picture path>";
}
You will have to do this in the client side - that is, using javascript.
You can add a client side onMouseOver="this.src = 'pathToOtherimage'" attribute and a similar one for onMouseOut to revert back.
It can't be done from the server-side (in the C# code), but rather must be done on the client-side (in JavaScript). Starting with that fact, there are various approaches to the subject.
I have a save button which when clicked should make some changes in the database.
if (bFound== false)
{
// Giving the warning message
// If user presses cancel then abort
// Prepare the list of dbId needs to be deleted
deletedBSIds.Add(dbId);
}
Here if the bFound field is true it should not execute the above statement, but if it is false it should go in the condition and then ask if the user want to save changes "yes" or "no".
If the user says yes it should go to the command "deletedBSIds.Add(dbId);" and keep executing further but if the user presses No it should basically abort and do nothing at all.
Is there a way to do this?
Any help would be appreciated.
This is a server side event. so i think cannot add a click event in my button/..
Here the message box only pops up if the bFoung field is false. or else it will not pop up at all.
Please correct me if u feel i am wrong..
thanks
You'll want to add the following to the button:
button.OnClientClick = "return ConfirmThis();";
You'll then need to add the ConfirmThis function to the Page:
Page.ClientScript.RegisterScriptBlock(GetType(), "ConfirmThis",
#"function ConfirmThis() {
if(condition) { //where condition checks the bfound element.
return confirm(""Are you sure you want to delete this?"");
}
return true;
}");
Doing this approach you're going to want to try and be able to test the bfound condition on the client side in the javascript. If the bfound value is stored in a textbox or HiddenField you should use the document.getElementById function. If the bfound value is known when you are creating the page, you can inject it into the ConfirmThis function directly, of pass it into the ConfirmThis function as a parameter.
Edit in response to your edit:
You have two options when trying to elicit a confirm from the user:
Using client side logic that is already sent to the browser to perform the confirm. This is the example that I have given above.
The "Other" option is to send the page back with a modal dialog, or using the confirm box. You will then get the user's confirmation back in a completely new postback to the server. So you'll need to rethink your logic to be able to temporarily store the information from the first post back and wait for the second post back to finalize the desired action.
Of the two examples, the first option is cleaner and requires no temporary memory and saves the user an additional postback.
Because both options are going to require you to rework the logic asking for the confirm, if at all possible I would try to convert the logic required for the condition to show the confirm dialog to be able to be performed on the client's computer with javascript.
Is there any way you can precalculate the bfound variable, or at the least, send enough information for it to be calculated on the client?
If you still feel like using option 2 after all of my pleading:
use the following code (based on http://www.dotnetspider.com/resources/1521-How-call-Postback-from-Javascript.aspx:
if(bfound)
{
//save all the information you need in temporary information
ViewState["InformationINeedToFinishAfterPostback"] = ImportantInformation;
Page.ClientScript.RegisterScriptBlock(GetType(), "postbackmethod", Page.ClientScript.GetPostBackEventReference(this, "MyCustomArgument"));
Page.ClientScript.RegisterStartupScript(GetType(), "startupconfirm",
#"if(confirm(""are you sure?"") {
__doPostBack('__Page', 'MyCustomArgument');
}");
}
Now to handle the postback add the following code to your page_load:
if(Request("__EVENTARGUMENT") == "MyCustomArgument")
{
ImportantInformation = (CastToAppropriateType)ViewState["InformationINeedToFinishAfterPostback"];
//finalize the desired action here.
}
But... I would still recommend the first option. But now you have the code you will need for both options. Also, I didn't test this code, so you're bound to encounter syntactic problems, but it gets you on the right track.
I'm not all that sure what bfound is supposed to represent, but you can't execute 1/2 way through some server code and then go back to the client- ASP.NET does not work that way.
Typically you will do the confirmation with some client side JavaScript. Google ASP.NET Yes/no confirm to find lots of different ways to do this...
Once you've done this you can then conditionally execute the server side code.
You could use the Javascript confirm() function to display a dialog box to the user with 'OK' and 'Cancel' prompts. You could then store the user's choice in a hidden field and trigger a postback. This article explains how to render Javascript code to the client using ASP.NET.
Since you are using ASP.NET you can add an attribute to your button:
btnDelete.Attributes.Add("onclick", "return confirm('Are you sure?');");
Where btnDelete is your Button.
The __doPostBack is not working in firefox 3 (have not checked 2). Everything is working great in IE 6&7 and it even works in Chrome??
It's a simple asp:LinkButton with an OnClick event
<asp:LinkButton ID="DeleteAllPicturesLinkButton" Enabled="False" OnClientClick="javascript:return confirm('Are you sure you want to delete all pictures? \n This action cannot be undone.');" OnClick="DeletePictureLinkButton_Click" CommandName="DeleteAll" CssClass="button" runat="server">
The javascript confirm is firing so I know the javascript is working, it's specirically the __doPostBack event. There is a lot more going on on the page, just didn't know if it's work it to post the entire page.
I enable the control on the page load event.
Any ideas?
I hope this is the correct way to do this, but I found the answer. I figured I'd put it up here rather then in a stackoverflow "answer"
Seems it had something to do with nesting ajax toolkit UpdatePanel. When I removed the top level panel it was fixed.
Hope this helps if anyone else has the same problem. I still don't know what specifically was causing the problem, but that was the solution for me.
Check your User Agent string. This same thing happened to me one time and I realized it was because I was testing out some pages as "googlebot". The JavaScript that is generated depends on knowing what the user agent is.
From http://support.mozilla.com/tiki-view_forum_thread.php?locale=tr&comments_parentId=160492&forumId=1:
To reset your user agent string type about:config into the location bar and press enter. This brings up a list of preferences. Enter general.useragent into the filter box, this should show a few preferences (probably 4 of them). If any have the status user set, right-click on the preference and choose Reset
I had this same problem (__doPostBack not working) in Firefox- caused a solid hour of wasted time. The problem turned out to be the HTML. If you use HTML like this:
<input type="button" id="yourButton" onclick="doSomethingThenPostBack();" value="Post" />
Where "doSomethingThenPostBack" is just a JavaScript method that calls __doPostBack, the form will not post in Firefox. It will PostBack in IE and Chrome. To solve the problem, make sure your HTML is:
<input type="submit" id="yourButton" ...
The key is the type attribute. It must be "submit" in Firefox for __doPostBack to work. Other browsers don't seem to care. Hope this helps anyone else who hits this problem.
this might seem elemental, but did you verify that your firefox settings aren't set to interfere with the postback? Sometimes I encounter similar problems due to a odd browser configuration I had from a debugging session.
Is it because you are doing return confirm? seems like the return statement should prevent the rest of the code from firing. i would think an if statement would work
if (!confirm(...)) { return false; } _doPostBack(...);
Can you post all the js code in the OnClick of the link?
EDIT: aha, forgot that link button emits code like this
<a href="javascript:__doPostBack()" onclick="return confirm()" />
Are you handling the PageLoad event? If so, try the following
if (!isPostBack)
{
//do something
}
else if (Request.Form["__EVENTTARGET"].ToLower().IndexOf("myevent") >= 0)
{
//call appropriate function.
}
Check if you are getting a call this way, if so then maybe the event is not wired and nedes to be explicitly called.
what do you expect from "Enabled = 'false'" ?
I have had problems with firebug on some web forms, something to do with the network analyser can screw with postbacks.
With or without the OnClientClick event it still doesn't work.
The _doPostBack event is the auto generated javascript that .NET produces.
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
*The &95; are underscores, seems to be a problem with the stackoverflow code block format.
Now that i think about it, as noted in my last edit, you want to drop the javascript: in the on client click property. It's not needed, because the onclick event is javascript as it is. try that, see if that works.
Seems it had something to do with nesting ajax toolkit UpdatePanel. When I removed the top level panel it was fixed.
Hope this helps if anyone else has the same problem.
I had this exact same issue in a web app I was working on, and I tried solving it for hours.
Eventually, I did a NEW webform, dropped a linkbutton in it, and it worked perfectly!
I then noticed the following issue:
...
I switch the order to the following, and it immediately was fixed:
...
IE had no issue either way (that I noticed anyway).
I had a similar issue. It turned out that Akamai was modifying the user-agent string because an setting was being applied that was not needed.
This meant that some .NET controls did not render __doPostBack code properly. This issue has been blogged here.
#Terrapin: you got this exactly right (for me, anyways).
I was running User Agent Switcher and had inadvertently left the Googlebot 2.1 agent selected.
In Reporting Services 2008 it was causing the iframes that reports are actually rendered in to be about 300x200 px, and in Reporting Services 2008 R2 is was throwing "__doPostBack undefined" errors in the Error Console.
Switching back to the Default User Agent fixed all my issues.
I had the same problem with Firefox. Instead of using __doPostBack() could you use the jQuery .trigger() method to trigger a click action on an element that has your postback event registered as the click action?
For example, if you had this element in your aspx page:
<asp:Button runat="server" ID="btnMyPostback" OnClick="btnMyPostback_Click" CssClass="hide" ToolTip="Click here to submit this transaction." />
And your postback event in your controller:
protected void btnMyPostback_Click(object sender, EventArgs e)
{
//do my postback stuff
}
You could do the postback by calling:
$("#btnMyPostback").trigger("click");
This will cause the Page_Load event to fire if you need to do something on Page_Load.