ASP.net button is clicked in every page refresh - asp.net

I have an asp.net button in my page, after I click the button, it is clicked again and again whenever I refresh the same page.
I tried;
if (!IsPostBack)
{
.....
}
for the click function of the button, but in this case button is not working.
<asp:Button ID="btnCommentSubmit" runat="server" Text="Submit" CssClass="leaveAComment" onclick="btnCommentSubmit_Click" />
above is the button.
protected void btnCommentSubmit_Click(object sender, EventArgs e)
{
string cityID = BusinessClass.Default.findCityIDByCountryAndCityName(Request.QueryString["city"].ToString(), "url").ToString();
BusinessClass.Default.makeComment(txtComment.Text, Session["userID"].ToString(), cityID);
txtComment.Text = null;
}
and this is the function.

If don't get you wrong your problem is when you hit F5 after clicking the button. Trying to resubmit the form is the normal behavior and is not related to asp.net but to browsers in general.
F5 causes to re-execute last request to the server, in your case, a POST request.
A way to avoid this issue is implementing the web pattern Post/Redirect/Get

Easy fix with a bit of JavaScript.
document.onkeydown = function() {
if(event.keyCode==116) {
event.keyCode=0;
event.returnValue = false;
}
}
This would stop the duplicate resend when you hit F5.

Related

Braintree Drop-In UI in ASP.NET web form with submit button method is not called when clicked

I have created a simple payment form where contains fields that accept amount, the drop-in UI and the submit button.
<form id="form1" runat="server">
<div>
<label>Amount:</label>
<asp:TextBox ID="txtAmount" runat="server" />
</div>
<div id="dropin-container"></div>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
<script src="https://js.braintreegateway.com/v2/braintree.js"></script>
<script>
braintree.setup("<%= this.ClientToken %>", "dropin", { container: "dropin-container" });
</script>
and the code behind
protected string ClientToken = String.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GenerateClientToken();
}
}
protected void GenerateClientToken()
{
var gateway = new BraintreeGateway
{
Environment = Braintree.Environment.SANDBOX,
MerchantId = "merchant-id",
PublicKey = "public-key",
PrivateKey = "private-key"
};
this.ClientToken = gateway.ClientToken.generate();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
var gateway = new BraintreeGateway
{
Environment = Braintree.Environment.SANDBOX,
MerchantId = "merchant-id",
PublicKey = "public-key",
PrivateKey = "private-key"
};
var request = new TransactionRequest
{
Amount = Convert.ToDecimal(this.txtAmount.Text),
PaymentMethodNonce = Request.Form["payment_method_nonce"]
};
Result<Transaction> result = gateway.Transaction.Sale(request);
}
After I load the page in the browser, I can see the form that accept amount and also the drop-in ui form which accept credit card and/or PayPal.
The issue is when I click Submit button, the method btnSubmit_Click doesn't get called. The page looks like it post back correctly but I cannot see any line of code within the btnSubmit_Click is executed.
I follow the instruction from this page:
https://www.braintreepayments.com/features/drop-in
But I really can't think of anything that I miss.
Anyone can help me with this issue would be very appreciated. Thank you so much.
Knott
I work at Braintree and can help you with this question.
Some background on what braintree.js is doing when you load the Drop-in on your page: it listens for form submissions, and when it detects one it will interrupt the form submit, communicate with Braintree to generate a nonce, and then run your callback if defined. What’s happening is that your .NET postback event is broadcasting a submit action – the same type of action that braintree.js interrupts in the first place.
As a workaround, you can try adding the following to your Page_Load code:
ClientScript.GetPostBackEventReference(this, string.Empty);
ClientScript.RegisterClientScriptBlock(this.GetType(), "PayEvent","<script>function PayEvent() {document.getElementById('__EVENTTARGET').value = '"+ btnSubmit.ClientID +"'; }</script>" );
btnSubmit.Attributes.Add("onClick", "PayEvent()");
Where btnSubmit is the ID of your button.
This should circumvent the submit interruption and allow your form to be submitted properly. In addition, this problem does not occur with our custom integration as an alternative.
Let us know if you have any further questions.
You just needed to put your transaction request code in a method and then call that sub on a post back rather than page load.
This way the auto submit won't interrupt with things.
Protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
GetClientToken();
} else {
Pay();
}
}
protected void Pay() {
PaymentMethodNonce = Request.Form["payment_method_nonce"]
//Build request string etc.
}
Brian,
Your solution above was supplied to me by PayPal support, but unfortunately, it doesn't solve the problem.
To be honest, it is this 'listening' (read: unreliable, 'clever code') to form submissions which is causing all the problems when one tries to integrate it in a Web Forms/UpdatePanel page - it really isn't designed for WebForms/UpdatePanels and requires all kinds of really messy code to make it work and synchronise properly. It is almost as if it was never designed for anything other than MVC or Java!
What would be a far better solution would be if we could attach a JavaScript call in OnClientClick of a button which synchronously calls BrainTree/PayPal via a JavaScript module hosted on PayPal which returns the nonce so that we can then do something with it. As it stands now, the Braintree/PayPal code intercepts a submit button (all buttons in WebForms are 'submits' by default, so this causes problems) and fires off a call asynchronously to get a nonce and at the same time, calls the button OnClick in the C# code. The net result is that the C# code runs before the Braintree/PayPal call returns and you can never synchronise the two.

Multiview calling button click event when in not active view

I have a multiview with two views. view at index 0 is "Readonly" and view at index 1 is edit view. by default is is set to show reaonly view with this :
<asp:MultiView ID="mv" runat="server" ActiveViewIndex="0">
I click a button I enter some information in view 1 and click save and it goes to view 0 with this code:
protected void SaveLinkButton_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
bool success = Save();
if (success)
{
LoadViewMode();
mv.ActiveViewIndex = 0;
}
}
}
Now after clicking save button, when I am in reaonly view. If I refresh the button, It calls save function again. I don't know why ?
Please suggest solution to it.
When you refresh the page (not the button), the last request that returned the page being viewed is resubmitted to the server. Therefore, the server executes the same code again.

hide asp label text before submitting on server

The problem looks very simple but it giving me pain
i am making a login page manually which checks for user email and password from linq. on login page there is an asp label which shows the error msg based on query result like "user not exist" or "user is inactive" etc. there are asp required field validators on both text boxes.
the problem is if user first attempt get unsuccessful and message get displayed on lable, it do't go away unless user get successfully loged in. i want the text back as lable1.text="" on submit button but it can't as its a server side control and the text box validators do't let it go if empty. do i have to use java script?
The easiest thing to do here would be to clear the messages in javascript, as you thought.
<asp:Button ID="SubmitButton" OnClientClick="ClearLableText" runat="server" />
And updated javascript, per your comment:
function ClearLableText() { var element = document.getElementById("<% this.lblMessage.ClientID %>"); element.innerHTML = ""; }
You can try this
protected void page_load(object sender, EventArgs e)
{
MyMessageLabel.Text = ""; //or .Visible = false;
}
protected void Button_Click(object sender, EventArgs e)
{
//By this time, page_load had already executed and the Message Label cleared
MyMessageLabel.Text = "new result from server";
if(validResult)
//RedirectToWhere();
else
//StayOnPage();
}
Hope it works for you.

ASP.NET WebForms + Postback then open popup

I have a LinkButton that has to postback to perform some logic.
Once it is finished, instead of loading the page back up in the browser, I want to leave it alone and pop open a new window.
So far, the best idea I've had is to put the LinkButton in an UpdatePanel, and have it render some JavaScript out when it reloads, yet I think that is totally hacky. Also, if I recall right, JavaScript within a update panel won't run anyways.
Any other ideas?
Use LinkButton.PostBackUrl to set a different page to POST to, and some client script to get a new window (and the old target restored so that future postbacks work normally). The 2nd page can use PreviousPage to get access to any needed state from the original page.
<script runat="server">
void lnk_Click(object sender, EventArgs e) {
// Do work
}
</script>
<script type="text/javascript">
var oldTarget, oldAction;
function newWindowClick(target) {
var form = document.forms[0];
oldTarget = form.target;
oldAction = form.action;
form.target = target;
window.setTimeout(
"document.forms[0].target=oldTarget;"
+ "document.forms[0].action=oldAction;",
200
);
}
</script>
<asp:LinkButton runat="server" PostBackUrl="Details.aspx" Text="Click Me"
OnClick="lnk_Click"
OnClientClick="newWindowClick('details');" />
Here is the code:
protected void Button1_Click(object sender, EventArgs e)
{
// Do some server side work
string script = "window.open('http://www.yahoo.com','Yahoo')";
if (!ClientScript.IsClientScriptBlockRegistered("NewWindow"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(),"NewWindow",script, true);
}
}
One thing you could try is to have your LinkButton OnClick event do its processing, then register a Page.ClientScript.RegisterStartupScript with the popup code, which will put some Javascript into the tag to fire off after the page loads. This should launch your new window after the processing completes.
EDIT: Reading your comment, I believe you can still use this approach, have your results stored in a session variable, and then have the popup page pull the results from there.

Prevent hiding of ModalPopupExtender when ok or cancel is clicked

I am using an ASP.NET ModalPopupExtender on a page and would like to prevent the dialog from hiding when the user presses the ok button in certain conditions. But I can't seem to find a way.
What I am looking for is something like this
ajax:ModalPopupExtender
...
OnOkScript="return confirm('You sure?')"
...
if confirm is false, then the modal dialog doesn't disappear.
From my understanding in your specific situation you would not wire up the button, and just wire up a script to handle the conditional, then you can close it via JS.
The following JavaScript function will allow you to achieve this:
function conditionalHide(clientID)
{
if (confirm('You sure?'))
{
$find(clientID).hide();
}
}
You can wire this up to your asp:Button control in the Page_Load event of your page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
btnOK.OnClientClick = string.Format("conditionalHide('{0}'); return false;",
panPopup_ModalPopupExtender.ClientID);
}
}
Some notes:
panPopup_ModalPopupExtender is your ModalPopupExtender
The return false; prevents a postback from occurring when the user clicks the button
You could hard-code the ClientID of the ModalPopupExtender, but this introduces an (additional) maintainance headache. The approach shown is the best one that I've found to alleviate this overhead

Resources