how to prevent refresh on asp.net c# web page button? - asp.net

how to prevent refresh on asp.net c# web page button?
protected void Button1_Click(object sender, EventArgs e)
{
}
Regards

you must use this way :
<asp:button ID="btn" runat="server" Text="Button" onClientclick="btn_Click(event);"> </asp:button>
<script>
function btn_Click (e)
{
if(//Check somthing)
e.preventDefault();
}
</script>

Short answer, you can't.
However, using methods such as ajax, you can hide the appearance of the postback.

you can do it by creating a cookie inside your Button1_Click method. The first instruction within this method should check if that cookie exists or has not expired. In case itdoesn't exist or it expired, the follow line will create or update the cookie. In case the cookie exists,
return;
Sorry i cant give code cause im using my mobile.

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.

How can I stop refreshing the page in the else condition

My code:
protected void btnOk_Click(object sender, EventArgs e)
{
if (txtReportFavorite.Text != string.Empty)
{
//..
}
else
{
Response.Write("<script>alert('Enter Favorite name.')</script>");
// I need to prevent page refresh here.
}
}
How can I stop refreshing the page in the else condition. Thanks.
You can't.
The new page has already been requested when that code runs. If you don't do a postback, that code will never run.
If you want to do the validation without doing the postback, you should do it using client code instead.
The fact that you got to the server side means that your page has done a full cycle to the server and refreshed itself.
Unless you are calling this code with an Ajax call.
You can also achieve this by placing an AjaxUpdatePanel around your button that will simulate an Ajax call when your clients will submit your form.
in your code behind on page load put this
btnOk.Attributes.Add("onclick","return validate();");
in your aspx file have this script
function validate()
{
if(document.getElementById("txtReportFavorite").value == "";
{
alert("Enter Favorite name");
return false;
}
}
Your page is already go to the server side and it is in already postback is progressing.
you have to use client side code for preventing postback.
why not to use RequiredFieldValidator if only empty textbox need to validate?
you can do it on client side.
<asp:TextBox runat="server" id="txtReportFavorite" />
<asp:RequiredFieldValidator runat="server" id="txtReportFavorite" controltovalidate="txtName" errormessage="Enter Favorite name!" />
<br />
<asp:Button runat="server" id="btnSubmit" text="Ok" onclick="btn_Click" />
protected void btnSubmitForm_Click(object sender, EventArgs e)
{
if(Page.IsValid) //for secure validation
{
//do something
}
}
Try using RegisterScriptBlock.
ClientScript.RegisterStartupScript(this.GetType),"","$(document).ready(function(){alert('Enter Favorite name.')});",true);
If you want to perform from server-side do it like above.. Otherwise many answers already posted.
The kind of functionality you are showing can be easily achieved by using a Validator so the page won't post back.
As once it reaches the server, its really not possible to stop the refresh. Well, at least as far as I know.
-Milind

asp.net server side event is not working

I have an button in my Jquery mobile page, which is using asp.net webform.
<asp:Button ID="btnSeacrh" runat="server" Text="Search" OnClick="btnSeacrh_Click" />
Which is enabling asp:panel via this simple code on backend
protected void btnSeacrh_Click(object sender, EventArgs e)
{
pnlSearch.Visible = true;
}
Now, when I am clicking this button nothing happened but the URL is extended with the # keyword.
Ex. Previously it was
http://localhost:4989/MobileApp/CreateOrderByText.aspx
After clicking
http://localhost:4989/MobileApp/CreateOrderByText.aspx#/MobileApp/CreateOrderByText.aspx
But it is not showing the panel.
Any help ?
The code you posted looks fine, so I would assume the problem is elsewhere: are there any javascript errors on the page?

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