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.
Related
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.
string LocalWorkSiteName = WorkSite.Site_Name;
System.Windows.Forms.MessageBox.Show("Are you sure you want to delete invoice " for " + LocalWorkSiteName);
1) Why does the pop up always appear behind the browser? I want it to load in front of the browser.
2) How can I add a 'Yes' and 'No' button and remove the current 'OK'? So in code behind, if 'yes' do one thing if 'no' do the other:
if(yesIsPressed)
{
...
}
if(noIsPressed)
{
...
}
Am I going about this the correct way or are there more suitable methods?
EDIT
Thanks for the reply guys...Going to go with the JS side, but I may need some assistance with it.
So my button:
<asp:Button runat="server" ID="RemoveInvoice" Text="Remove Invoice" OnClick="RemoveInvoice_Click" CssClass="FadeOutOnEdit" />
runs the code behind function 'RemoveInvoice_CLick'...can I also get it to run the JS or do I need to change it to an input button and then do the code behind updates from there
Maybe something like this:
DialogResult result1 = System.Windows.Forms.MessageBox.Show("Are you sure you want to delete invoice for " + LocalWorkSiteName,
"Important Question",
MessageBoxButtons.YesNo);
if(result1 == DialogResult.Yes) { ... }
if(resutl1 == DialogResult.No) { ... }
Note*
But you shouldn't do that with MessageBox :), because that is for desktop app (System.Windows.Forms), you should use some jQuery or javascript code for it.
It even won't show on your client side, it will only popUp on your server.
You can try with jQueryUI Dialog
You're loading a Windows Forms message box in a web page -- that's a control for a desktop app, not a web app. You'd probably be better served using a JavaScript popup, which is a web control. Using jQuery, you could attach a callback to a button's click event:
$("#buttonid").click(function() {
var answer = confirm("Are you sure you want to delete invoice for " + LocalWorkSiteName + "?");
if (answer)
{
// post to server-side
}
});
Or if you want to stick with an ASP.net button control, you could wire up the event handler in its tag:
<asp:Button id="RemoveInvoice" runat="server" Text="Remove Invoice"
OnClick ="RemoveInvoice_Click"
OnClientClick="return confirm('Are you sure you want to delete invoice?');"
CssClass="FadeOutOnEdit" />
The OnClientClick attribute will prevent the server-side event from firing if the code returns false, which is what happens if the user clicks Cancel on the JavaScript popup from the call to confirm.
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");
}
It looks like the Internet Explorer demon has struck again, and I cannot seem to figure this one out:
I have an ImageButton using OnCommand to delete a specific entry from my database. I however have implemented it so that the user will first confirm that they want to delete a specific item.
Here is the code for my ImageButton
<asp:ImageButton runat="server" ID="imgDelete" ImageUrl="~/Controls/TaskDetails/Images/delete.png" OnCommand="Tag_DeleteCommand" Visible='<%# CanDelete %>' OnClientClick="javascript:confirmDialog(this, 'Remove Tag','Are you sure you want to remove this tag?', 1); return false;"
CommandArgument='<%# Eval("TagID") %>' />
And here is my ConfirmDialog function
function confirmDialog(sender, title, message, type) {
//type entities
//1 = warning
//2 = error
//3 = success
//4 = Information
var sender = $(sender);
$("#message_dialog_inner_text").html(message);
$("#message_dialog_message_container").dialog({
modal: true,
title: title,
zIndex: 10003,
dialogClass: (type > 0) ? "message_dialog_type_" + type : "",
position: 'center',
buttons: {
"OK": function () {
//the yes option was selected, we now disable the onclientclick event, and fire the click event.
$(this).dialog("close");
if (sender.hasAttr("href")) {
window.location = sender.attr('href');
} else {
sender.removeAttr("onclick");
sender.trigger("click");
}
},
"Cancel": function () { $(this).dialog("close"); }
}
});
return false;
}
This works fine in Chrome, FF, Safari, but IE is just ignoring it and doing the postback. I have even changed my OnClientClick to "return false;" and it seems to have no impact on the button posting back. I have also changed it from an ImageButton to just a Button, to no avail. I am assuming it has something to do with the OnCommand event, but right I am at a loss! I have implemented this througout a pretty huge application, so I would like to manage the scope of the change. If anyone has some input, it would be greatly appreciated!
EDIT
OK, let me also just stress, I don't want it to post back, and even if I just have OnClientClick="return false;" the command button is still posting back (not what you would expect).
Here is the rendered markup from my ImageButton control
<input type="image" name="ctl00$body$pnlContentRight$pnlCurrentTaskDetails$repTags$ctl00$tagItem$imgDelete" id="ctl00_body_pnlContentRight_pnlCurrentTaskDetails_repTags_ctl00_tagItem_imgDelete" src="Controls/TaskDetails/Images/delete.png" onclick="javascript:confirmDialog(this, 'Remove Tag','Are you sure you want to remove this tag?', 1); return false;" style="border-width:0px;">
This isn't a resolution to your specific issue, but it's a workaround you may want to consider (I've used it in a couple of places):
Make your "delete" button a simple image, not a postback button.
Give it an OnClientClick which calls a local javascript function (passing the relevant data - at a minimum, the ID of the item to be deleted).
That local JS function loads the relevant data into a hidden var (so it can be accessed in your code-behind), and opens the jQuery confirm dialog.
That dialog is configured with NO jquery-dialog buttons. Instead, the launched DIV contains two asp:Buttons: ok and cancel. The cancel button simply closes the jQuery dialog. The OK button is a normal postback button with a server-side OnClick function.
Thus, the page is only posted-back if the user clicks the OK button on the confirm dialog. The confirm-dialog-event function knows which item to delete because that item's ID is in the hidden field.
This is probably not the "right" way to implement this behavior (from an ASP.NET purist standpoint). However, as workarounds go, I don't think it's too painfully kuldgey. And in my experience, it seems to work across all browsers (assuming they have JS enabled, of course). HTH.
You're OnClientClick is always returning false, which means that the event will never be executed. Try returning the input from the confirm like this:
OnClientClick="return confirmDialog(...);"
You will need to make sure that there is a way to return true from the confirmDialog function too. It looks like that function always returns false too.
I'm not very familiar with the jQuery UI dialog, but in concept it should work like this:
buttons: {
"OK": function () { return true; }, //perform a postback and execute command
"Cancel": function () { return false; } //abort postback and do nothing
}
I have a ListView that contains playlists. If the user wants to edit an album, they click the edit link and it allows them to remove or add songs to the playlist. If the user wants to Save a new playlist while keeping the original one, the would click a Save As Button. Here is what should happen:
If the user clicks Save As and they have not changed the name, I want to display an alert telling them they must change the name.
If the user clicks the Save As and they have changed the name, I want to display an a confirmation that they actually want to save it.
Currently, what is happening is that if I put something like the following in my code behind, the script does not register until the second click and whatever script was registered stays registered meaning that if I end up changing the name and the alert script was registered before, it will display the alert instead of the confirmation. Here is the code:
if (newname == oldname)
{
btnSaveAs.OnClientClick =
"javascript:alert('Save As requires you to change the name of the playlist. Please
change the name and try again.');";
}
else
{
btnSaveAs.OnClientClick = "javascript:confirm('Are you sure you want to save the
playlist" + newname + "?');";
}
I also tried adding the return false so it would not do a postback, but if I do that, then it does not doesn't actually do anything when I click OK on the confirmation.
What SLaks said is correct, you're misunderstanding the page lifecycle. The javascript code needs to be in place on the page before you click Save As. In your example as described, the user makes changes to the title/name and clicks Save As, after which the javascript code is applied to the button. The second time they click Save As, the validation results from the previous example pop up.
Option 1: Use a validator control
The simplest way to solve this is to use a RegularExpressionValidator control to compare the values.
Markup snippet:
<asp:Label ID="lblName" runat="server" Text="Name: " />
<asp:TextBox ID="txtName" runat="server" />
<asp:RegularExpressionvalidator ID="valName" runat="server" ControlToValidate="txtName" ErrorMessage="You must change the name before saving" Display="Dynamic" />
<asp:Button ID="btnSaveAs" runat="server" OnClick="btnSaveAs_Click" Text="Save As" CausesValidation="True" />
In your code-behind once the form fields (album name, etc.) are bound, run this:
valName.ValidationExpression = string.Format("[^{0}]", Regex.Escape(lblName.Text));
The above regular expression will be valid for any input except what was there to begin with. If the user changes the text for the album name, the save button will validate correctly. If they do not, the validator will kick in and display a message on the page saying they have to change it.
Then handle the OnClick event of the save button only for saving the values, because it will only fire if the page was validated:
protected void btnSaveAs_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//do you save actions as needed
}
}
You can also still use your confirm box as you wanted, by doing:
protected void Page_Load(object sender, EventArgs e)
{
btnSave.OnClientClick = "return confirm('Are you sure you wish to change the name?');";
}
The above should work just fine. An alternate approach is listed below:
Option 2: Use a clientside validation function
If you wanted to do the validation completely client side, you could but it will be far more complicated. What you'd need to do, is register a completely clientside validation function.
In your code behind during Page_PreRender:
protected void Page_PreRender(object sender, EventArgs e)
{
//define the script
string script = #"
function validateAlbumName(oldName, textBoxId) {
//get the textbox and its new name
var newName = document.GetElementById(textBoxId).value;
//compare the values
if (newName === oldName) {
//if the name hasn't changed,
alert('You must change the name of the album');
return false;
}
return confirm ('Are you sure you want to save the playlist ' + newName);
}
";
//register the client script, so that it is available during the first page render
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "SaveAsValidation", script);
//add the on client click event, which will validate the form fields on click the first time.
btnSaveAs.OnClickClick = string.Format("return validateAlbumName('{0}','{1}');", txtAlbumName.Text, txtAlbumName.ClientID);
}
Hope this helps. There are likely some syntax errors in the above as I just threw it together quickly..
The OnClientClick property is a Javascript string, not a URI. Therefore, you should not begin it with javascript:.
To handle the confirm correctly, write OnClientClick = "return confirm('Are you sure?');";
Also, you're misunderstanding the ASP.Net page model.
Your C# code-behind event handler only runs after the user clicks the button and after the OnClientClick callback. You need to write all of that in Javascript and call it in OnClientClick.