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).
Related
I want to call server side function based on user response on sweetalert in my javascript function. I tried using non ajax function, with 2 buttons solution. One button to show sweet alert and second button called inside sweet alert.
HTML Code (2 button) :
<asp:Button runat="server" ID="DelUser" Text="" style="display:none;" OnClick="DeleteEvent"/>
<asp:Button ID="DeleteUser" runat="server" Text="Delete User" Width="122px" BackColor="#FF572D" Font-Bold="True" OnClick="DeleteUser_Click" />
JS Function and sweetalert source :
<script src="https://unpkg.com/sweetalert#2.1.2/dist/sweetalert.min.js"></script>
<script type="text/javascript">
function delalert() {
swal({
title: "Are you sure?",
text: "Are you sure that you want to delete this data?",
icon: "warning",
buttons:true,
dangerMode: true,
})
.then(willDelete => {
if (willDelete) {
document.getElementById("DelUser").click();
}
else {
swal("Safe!", "Your imaginary file is safe!", "success");
}
});
}
And in my server side code (aspx.cs):
protected void DeleteUser_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "Popup", "delalert()", true);
}
protected void DeleteEvent(object sender, EventArgs e)
{
Response.Write("ASSSSSDASDASDASDSDSD");
}
Else function works just fine but when i click ok it shows nothing, the DeleteEvent not called. How can i solve this ?
What you have looks ok, except for the hidden button selector. Just add the tag ClientIDMode="static".
Or, you can of course use this:
getElementById('<%= DelUser.ClientID %>');
However, you have this backwards. The user does not click on server button, and THEN you in code behind attempt to inject + run the js dialog box.
You don't need that part in your code behind - REMOVE the script register.
However, there is a NICE trick you can use here, and thus only need ONE button.
And BETTER YET you don't have hard code the button. So, in theory, you could make a general routine and even one that you trigger from code behind. (but, you would have to pass the button to click as part of that setup). but, lets deal with one issue at a time here.
As we know, most jQuery/js dialog boxes of course don't wait. So, then you can't really return true/false, since the js code runs, and returns the value and THEN pops up the dialog box. So, a common solution is of course your duel button, and the hidden button trick.
However, you can actually make this work with JUST one button, and not really much of any code change here. And as noted, bonus points, since this also lets you use/get/pass the location of the button click.
so, assume this button click:
<asp:Button ID="Button1" runat="server" Height="31px" Text="Button" Width="159px"
OnClientClick="return delalert(this);"
OnClick="Button1_Click" />
Note how I do NOT hide the button. You ONLY need the one button.
But, your alert code now becomes this:
<script>
var delalertok = false
function delalert(btn) {
if (delalertok) {
delalertok = false
return true
}
swal({
title: "Are you sure?",
text: "Are you sure that you want to delete this data?",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then(willDelete => {
if (willDelete) {
delalertok = true;
btn.click();
}
else {
swal("Safe!", "Your imaginary file is safe!", "success");
}
});
return false;
}
</script>
Note how we added a global delalertok. The initialization of js code ONLY runs the first time on page load. So, we set that value = false.
Note how we passed the button - so we don't need to change the alert code for different buttons on the same page.
Note also how the last line of the routine returns false.
Note also how by passing the button, we can "click" it again.
So, you click on your button. js code runs, pops dialog - returns false. Server side button did not run.
Note the dialog is popped up. If user hits ok, then your code stub runs, clicks the button, but BEFORE we click, we set that value = true. So now the click button runs again, it sees true in the first lines of the jscode, and thus your button will "now" get a return true - and will run the server side event.
We thus do not need nor require any server side register script here.
Based on the answer I found here :
Link for Reference
The problem seems on my
document.getElementById("DelUser").click();
And the HTML I'm referencing at.
So the solution would be :
Reference the dynamic name
document.getElementById("<%= DelUser.ClientID %>").click();
In .NET4 we can use ClientIDMode="Static"
The HTML Code then becomes :
<asp:Button runat="server" ClientIDMode="Static" ID="DelUser" Text="" style="display:none;" OnClick="DeleteEvent"/>
And called like previous method :
document.getElementById("DelUser").click();
Either way it will work just fine.
I am working on an asp.net webforms project. On a page, I have an asp.net button which would remain disabled. This button will be enabled after a javascript event. When the button is clicked, first I want to execute a javascript function and then a code-behind function. The problem is that only the code-behind function is called. However, if the button is enabled all the time, which means Enabled="false" attribute is not present in the asp.net button, then it first calls the js function and then goes to the code-behind. Is there any way to make the button disabled when the page loads and then programmatically enable it from js?
<asp:button id="btnSave" ClientIdMode="Static" runat="server" Enabled="false" Text="Save"
onClientClick="javascript:return btnSave_ClientClick();" onclick="btnSave_Click"
CssClass="buttonStyle"></asp:button>
function btnSave_ClientClick(){
//js function - do something
}
protected void btnSave_Click(object sender, System.EventArgs e)
{
//code behind - do something
}
You should be able to enable the button in the usual html/js way, because the button is already on the page, rendered in html:
function enableBtn(){
document.getElementById("btnSave").disabled = false;
}
You could put that one line inside another function, but you won't be able to use it from the btnSave button, because, obviously, it's disabled. Hth.
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.
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.
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");
}