Stop page reload of an ASP.NET button - javascript

NET application, I have inserted a button that call a Javascript function (OnClientClick event) and a VB.NET function (OnClick event)
<asp:Button OnClientClick="jsfunction() " OnClick="vbfunction" Text="Submit" runat="server" />
The problem is that when I click the button, it refreshes the page and delete the content of the text boxes.
I have tried with inserting return false; on the OnClienClick event, but it doesn't execute the OnClick Event.
How can I avoid the page reload ?
P.S.: At the end of the Javascript function a new window is opened window.open(newWindow.aspx), but I want that the first page mantain the value inserted by the user in the Text Boxes.
Thanks in advance :)

You need to use return statement at two points.
OnClientClick="return jsfunction();"
function jsfunction()
{
//
return false;
}
OR, you can return false after the function call like this.
OnClientClick="jsfunction(); return false;"
Note if you want to do postback conditionally then you need to return true or false.
OnClientClick="return jsfunction();"
function jsfunction()
{
if(conditionForPostBack)
return true;
else
return false;
}

or you can disable the submit behaviour. By default asp.net renders button as submit button. if you disable submit behaviour it will render button as button type
<asp:Button UseSubmitBehavior="false" OnClientClick="jsfunction() " OnClick="vbfunction" Text="Submit" runat="server" />
But with this code it will not fire server side event "OnClick"

if you are not going to trigger the button with C# Codebehind function, then you dont need to use asp:Button. Therefore you can use a regular html .
<button id='btn_1' onclick='ajax_function()'>Button</button>
html button is much easier and faster. if you use asp:button, then you should use clientid() function to catch the control to trigger the ajax.

Searching for the same thing as you i find a patch:
If you call a method server side, you can use AJAX with the update panel, but that didn't worked for me. But you can save what you want in Session, so you have it as far as Session lasts.
// Save at SessionParameter the elementToSave we want.
this.Session["SessionParameter"] = elementToSave;
// Retrieve the info from the Session
ElementYouNeededToSave = (TypeOfTheElement)Session["SessionParameter"];
Hope this will help someone in my situation.

Related

C#/ASP web, ASP:Checkbox to do messagebox on client side, if yes run server side code

I apologize if this has been answered somewhere but I could not find my particular problem's answer.
I have a asp object:
<asp:CheckBox ID="chkRemove" runat="server" Checked='<%#Convert.ToBoolean(Eval("CommonWord")) %>' OnCheckedChanged
= "OnCheckedChanged_CommonWord" AutoPostBack="true" />
Basically I want to show a message box asking if its ok to remove, if no or cancel is selected, don't do a postback (or don't run any server side code), and if yes then run that function "OnCheckedChanged_CommonWord".
I tried doing a javascript Confirm() call which pops up but if I press yes, the C# server side code does not run ("OnCheckedChanged_CommonWord") the "no" or "cancel" works perfectly as it doesn't do a postback.
P.s. Please no AJAX due to server restrictions for me.
The Checkbox control actually lacks any type of OnClientCheckChanged event that can be used to manage if a PostBack should occur or not (like OnClientClick, etc.) based on a client-side event.
But you should be able to accomplish this using an onclick attribute with a function to manage the default PostBack by calling it manually :
<asp:CheckBox ID="chkRemove" runat="server"
Checked='<%#Convert.ToBoolean(Eval("CommonWord")) %>'
OnCheckedChanged="OnCheckedChanged_CommonWord"
AutoPostBack="true"
onclick='return OnClientCheckChanged("Are you sure you want to do this?",this);' />
<script>
function OnClientCheckChanged(prompt,source) {
if (confirm(prompt)){
__doPostBack("'" + source.id + "'", '');
return true;
}
else {
return false;
}
}
</script>
When the CheckBox is actually clicked, it will trigger your confirm() prompt and based on the result, it will either trigger an explicit PostBack (via the nasty __doPostBack() call or it won't do anything.
I'm not a huge fan of the __doPostBack() call, but it seems like an appropriate solution here.

when to call the Server onClick vs OnClientClick

Can someone please explain why btnSaveFile1 is clicked, onClientClick() is called and if onClientClick() returns true it calls the server but if onClientClick() returns false it doesn't call the server. Which I understand fully.
But why isn't that the case for btnSaveFile2 it seems to never call the server no matter what onClientClick() returns ?
Why does the return false; have to be inline ?
<asp:Button ID="btnSaveFile1" runat="server" Text="Save" OnClientClick="if(!onClientClick()){return false;}" OnClick="btnSaveFile_Click" UseSubmitBehavior="false" />
<asp:Button ID="btnSaveFile2" runat="server" Text="Save" OnClientClick="return onClientClick()" OnClick="btnSaveFile_Click" UseSubmitBehavior="false" />
<script type="text/javascript">
function onClientClick() {
if (CurrentMemberValidatedWindow()) {
if (!ValidateForm()) {
return false;
}
}
else {
DeleteInvalidFiles();
return false;
}
return true;
}
</script>
TL;DR: remove UseSubmitBehavior="false"
Longer explanation:
Use the UseSubmitBehavior property to specify whether a Button control
uses the client browser's submit mechanism or the ASP.NET postback
mechanism. By default the value of this property is true, causing the
Button control to use the browser's submit mechanism. If you specify
false, the ASP.NET page framework adds client-side script to the page
to post the form to the server.
If you look at the page source, the onclick for the rendered button isn't simply "if(!onClientClick()){return false;}" or "return onClientClick();", because it has to add client-side script to post the form. So now for the first button it is:
"if(!onClientClick()){return false;};__doPostBack('ctl00$MainContent$btnSaveFile1','')"
and for the second it is
"return onClientClick();__doPostBack('ctl00$MainContent$btnSaveFile2','')"
So you can see in case #2, if it returns true, it will not reach the script that actually submits the form. (this is not the case for button 1, which does reach the script and thus submits the form).

To give a confirm pop up box within event for submit button and allow or not allow to submit

I have submit button. On its click I have to check a paricular field's value from database and then give a pop up for confirmationa and then depending on yes or no allow/disallow save.How can i do so..
On using confirm JS function it passes the statement and runs the Save procedure anyway.
my button's event
protected void btnSubmit_Click(object sender, EventArgs e)
{
string ListExam = string.Empty;
DataTable dt = BussObjGoalCert.CheckPlannedStatus(custObjGoalCert);
if (dt.Rows.Count != 0)
{
for (int i = 0; i < (dt.Rows.Count); i++)
{
ListExam = ListExam + (dt.Rows[i]["MultipleExamPlanned"]) + ";";
}
lblExamMultiple.Text = ListExam;
string myScript2 = "confirm('Unselected exam planned under other certification will also be unplanned.Do you wish to continue?');";
ClientScript.RegisterStartupScript(this.GetType(), "myScript", "confirm('Unselected exam planned under other certification will also be unplanned.Do you wish to continue?');", true);
}
Result = BussObjGoalCert.InsertGoalCertification(custObjGoalCert);
}
SO what I am doing is checking some data from backend and then trying to conditionally call the confirm function.
It IS CALLED but then Insert statement is also run irresepective of what the person chooses.
How can the database check be done within JS function.I need to do it in code behind. and yet allow/disallow complete save.How is this to be accomplished. I am not using OnCLientCLick as suggested in the answers.
Try this
If you have asp button
<asp:Button runat="server" ID="btn"
OnClientClick="return confirm('Are you surely want to submit (server button) ?');"
Text="Server button" />
If you have submit HTML button
<input type="submit"
onclick="return confirm('Are you surely want to submit (client button) ?');"
value="Client button" />
UPDATE
If you want to do this
Execute some server side code
Ask user for some confirmation
On user's confirmation execute some more server side code
Then should do following
Create a web service.
Use Jquery or Javascript to execute your server side code through that web service.
Display confirm box on complete(success) event of your web service request.
If user click's on YES perform a server side potback or perform one more web service request to execute the code to be executed on user's confirmation.
I think you are trying onclick event on submit button.
try onsubmit="return confirm('Are You sure to submit')" within form element
There is one solution for your problem.please follow these steps :
1.)On button's OnClientclick event call pagemethod and pass value in it which you want to check in Database.
2.)pagemethod is used to call server side static methods on client side and return result.
3.)Then return bool value from that in true if data exist and false if new.
4.)When flag is true then show confirmation box if confirmation is true then call server method again and update info and then return true to OnClientClick event.
OR
if confirmation is false then return false to OnClientClick event.
You can check my artical HERE.Hope this helps you.If you need more detail then please let me know.
try this
<asp:Button ID="btnsave" runat="server" Text="Save" OnClientClick="javascript:return Checkdelete();"/>
function Checkdelete() {
return confirm("Are you sure you want to Save the records");
}

javascript confirm asp.net button never submits?

i have a regular asp:button. I am working in .Net 3.5. I've tried adding a js confirm to the button with the OnClientClick attribute as well as adding in code-behind and the result is the same. No matter what the user clicks in the confirm pop-up the form will not submit??
BtnDeleteSelected.Attributes.Add("onclick", "return confirm('Are you sure you want to delete?');");
The confirm dialog appears and if i select "OK" it still does not submit.. Any ideas? thanks.
That's because you should not be returning in all cases. If you view the source of the page and look for the button markup, you are likely to see this...
onclick="return confirm('Ok?'); __doPostback();"
The __doPostback invocation is inserted automatically by the ASP.NET framework in some cases. Since you return immediately regardless of the result of confirm, the postback never fires. The ultimate solution would be to not to set the onclick attribute, but instead use an unobtrusive approach. However, if there is pressing reason to control this on the server-side via onclick, you can use a simple if statement and only return when they press "Cancel"...
string js = "if(!confirm('Are you sure you want to delete?')) return false;";
BtnDeleteSelected.Attributes.Add("onclick", js);
I had this problem too. I was using adding the client side javascript in the OnItemCreated code of a datagrid like this:
myTableCell = e.Item.Cells(iDeleteColumnNumber) 'Delete Button Column
myDeleteButton = myTableCell.Controls(1)
If myDeleteButton.UniqueID = "lbtnDelete" Then
myDeleteButton.Attributes.Add("onclick", "if(!confirm('OK to Delete?'))return false;")
End If
For some reason that didn't work. I then moved the JavaScript to the <asp:linkbutton> in the design view like this:
<asp:LinkButton id="lbtnDelete" runat="server" CssClass="link-text" Text="<img border=0 src=../images/icons/icon-delete.gif alt=Delete>"
CommandName="Delete" CausesValidation="false" OnClientClick="if(!confirm('OK to Delete?'))return false;"></asp:LinkButton>
And that worked for me.
Do you have to return TRUE if validation passes? Meaning, if confirm() returns false I don't think the form will submit.
Your code looks OK on the surface. Do you have any validators that might be preventing it being submitted? Try adding BtnDeleteSelected.CausesValidation = false to prevent the delete button calling any client-side validators.
Please try calling doPostBack function ;)
I mean:
BtnDeleteSelected.Attributes.Add("onclick", "CheckConfirm();");
<script language="javascript">
function CheckConfirm()
{
if ( confirm('Are you sure you want to delete?') )
__doPostBack('BtnDeleteSelected','');
else
return false;
return true;
}
</script>
Hope that helps,

ASP.NET postback with JavaScript

I have several small divs which are utilizing jQuery draggable. These divs are placed in an UpdatePanel, and on dragstop I use the _doPostBack() JavaScript function, where I extract necessary information from the page's form.
My problem is that when I call this function, the whole page is re-loaded, but I only want the update panel to be re-loaded.
Here is a complete solution
Entire form tag of the asp.net page
<form id="form1" runat="server">
<asp:LinkButton ID="LinkButton1" runat="server" /> <%-- included to force __doPostBack javascript function to be rendered --%>
<input type="button" id="Button45" name="Button45" onclick="javascript:__doPostBack('ButtonA','')" value="clicking this will run ButtonA.Click Event Handler" /><br /><br />
<input type="button" id="Button46" name="Button46" onclick="javascript:__doPostBack('ButtonB','')" value="clicking this will run ButtonB.Click Event Handler" /><br /><br />
<asp:Button runat="server" ID="ButtonA" ClientIDMode="Static" Text="ButtonA" /><br /><br />
<asp:Button runat="server" ID="ButtonB" ClientIDMode="Static" Text="ButtonB" />
</form>
Entire Contents of the Page's Code-Behind Class
Private Sub ButtonA_Click(sender As Object, e As System.EventArgs) Handles ButtonA.Click
Response.Write("You ran the ButtonA click event")
End Sub
Private Sub ButtonB_Click(sender As Object, e As System.EventArgs) Handles ButtonB.Click
Response.Write("You ran the ButtonB click event")
End Sub
The LinkButton is included to ensure that the __doPostBack javascript function is rendered to the client. Simply having Button controls will not cause this __doPostBack function to be rendered. This function will be rendered by virtue of having a variety of controls on most ASP.NET pages, so an empty link button is typically not needed
What's going on?
Two input controls are rendered to the client:
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
__EVENTTARGET receives argument 1 of __doPostBack
__EVENTARGUMENT receives argument 2 of __doPostBack
The __doPostBack function is rendered out like this:
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
As you can see, it assigns the values to the hidden inputs.
When the form submits / postback occurs:
If you provided the UniqueID of the Server-Control Button whose button-click-handler you want to run (javascript:__doPostBack('ButtonB',''), then the button click handler for that button will be run.
What if I don't want to run a click handler, but want to do something else instead?
You can pass whatever you want as arguments to __doPostBack
You can then analyze the hidden input values and run specific code accordingly:
If Request.Form("__EVENTTARGET") = "DoSomethingElse" Then
Response.Write("Do Something else")
End If
Other Notes
What if I don't know the ID of the control whose click handler I want to run?
If it is not acceptable to set ClientIDMode="Static", then you can do something like this: __doPostBack('<%= myclientid.UniqueID %>', '').
Or: __doPostBack('<%= MYBUTTON.UniqueID %>','')
This will inject the unique id of the control into the javascript, should you wish it
Per Phairoh: Use this in the Page/Component just in case the panel name changes
<script type="text/javascript">
<!--
//must be global to be called by ExternalInterface
function JSFunction() {
__doPostBack('<%= myUpdatePanel.ClientID %>', '');
}
-->
</script>
Using __doPostBack directly is sooooo the 2000s. Anybody coding WebForms in 2018 uses GetPostBackEventReference
(More seriously though, adding this as an answer for completeness. Using the __doPostBack directly is bad practice (single underscore prefix typically indicates a private member and double indicates a more universal private member), though it probably won't change or become obsolete at this point. We have a fully supported mechanism in ClientScriptManager.GetPostBackEventReference.)
Assuming your btnRefresh is inside our UpdatePanel and causes a postback, you can use GetPostBackEventReference like this (inspiration):
function RefreshGrid() {
<%= ClientScript.GetPostBackEventReference(btnRefresh, String.Empty) %>;
}
While Phairoh's solution seems theoretically sound, I have also found another solution to this problem. By passing the UpdatePanels id as a paramater (event target) for the doPostBack function the update panel will post back but not the entire page.
__doPostBack('myUpdatePanelId','')
*note: second parameter is for addition event args
hope this helps someone!
EDIT: so it seems this same piece of advice was given above as i was typing :)
If anyone's having trouble with this (as I was), you can get the postback code for a button by adding the UseSubmitBehavior="false" attribute to it. If you examine the rendered source of the button, you'll see the exact javascript you need to execute. In my case it was using the name of the button rather than the id.
Have you tried passing the Update panel's client id to the __doPostBack function? My team has done this to refresh an update panel and as far as I know it worked.
__doPostBack(UpdatePanelClientID, '**Some String**');
First, don't use update panels. They are the second most evil thing that Microsoft has ever created for the web developer.
Second, if you must use update panels, try setting the UpdateMode property to Conditional. Then add a trigger to an Asp:Hidden control that you add to the page. Assign the change event as the trigger. In your dragstop event, change the value of the hidden control.
This is untested, but the theory seems sound... If this does not work, you could try the same thing with an asp:button, just set the display:none style on it and use the click event instead of the change event.
You can't call _doPostBack() because it forces submition of the form. Why don't you disable the PostBack on the UpdatePanel?

Categories