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.
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 built a gridview in ascx page of a user control with custom button inside the command column and I tried to manage the CustomButtonClick in the ClideSideEvents, like this:
(ASCX)
<dx:GridViewCommandColumnCustomButton ID="ASPxCustomCommandButton1"/>
<ClientSideEvents CustomButtonClick="OnCustomButtonClick" />
(JAVASCRIPT)
function OnCustomButtonClick(s, e) {
if (e.buttonID == 'ASPxCustomCommandButton1') {
e.processOnServer = false;
PopupControlUpload.Show();
PopupControlUpload.PerformCallback(e.visibleIndex);
(VB)
Private Sub ASPxGridView1_CustomButtonCallback(sender As Object, e As ASPxGridViewCustomButtonCallbackEventArgs) Handles ASPxGridView1.CustomButtonCallback
Select Case e.ButtonID
Case "ASPxCustomCommandButton1"
//do something"
End Select
i can't get the id of button in javascript and i can't go in vb callback as conseguence. how can i do that in a user control? seems that "e" is not defined so he can't get buttonID from it. In the normal web page it work, but in the user control give me that issue.
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");
}
I have a simple ASP.net page where users can edit information about themselves.
When "Edit" button is clicked, the form goes into edit mode and I display "Save" and "Cancel" buttons, which behave as expected.
What I want to do is this:
When "Save" is clicked, display a Javascript Confirm dialog asking the user if they want to send an email to the other users to inform them of the update just made.
If user says OK, then execute all server-side code to save the data, AND send an email.
If user says Cancel, then execute all server-side code to save the data, WITHOUT sending the email.
So, I need the javascript box to set a flag which can then be read server-side, somehow... then I can do something like:
Sub btnSave_Click(sender, e) Handles btnSave.Click
'Save all the data
If sendEmail Then 'This flag set by reading result of javascript Confirm
'Send the email
End If
End Sub
I know how to add a Confirm box to the button Attributes, and have done so. I'm looking for an answer on how to read the result of that box on server side... in other words, I ALWAYS want the Page postback to happen (from clicking the button), but only SOME of the event-handler code to execute.
Hope that makes sense.
Thanks
Matt
Create a hidden field, and set the value of that field based on the result of the confirmation. You haven't shown the code/HTML for your button or form, but can you fit something like this into it:
<input type="hidden" id="sendEmail" name="sendEmail" value="" />
<input type="submit" value="Save" onclick="promptForEmail();" />
<script>
function promptForEmail() {
var result = Confirm("Send everybody an email?");
// set a flag to be submitted - could be "Y"/"N" or "true"/"false"
// or whatever suits
document.getElementById("sendEmail").value = result ? "Y" : "N";
}
</script>
There are several ways to do it but I am going to use asp:HiddenField. In javascript, after user confirms, let its result to be set in the hidden field. And in server side, you can access it like any other asp.net control.
So
your aspx:
<asp:HiddenField ID="HiddenField1" runat="server" Value="" />
CodeBehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var result = HiddenField1.Value;
}
}
Javascript:
//after confirm call this
function SetValue(val)
{
document.getElementById('HiddenField1').value=val;
}
I have a form submit button that has asp.net validators hooked up to it. If I make a javascript function to change the text to processing on click it does not work. The button flags the validators and also causes the whole page to post back. Heres the code I have:
C#
protected void Page_Load(object sender, EventArgs e)
{
btnPurchase.Attributes["onClick"] = "submit()";
}
Html
<script type="text/javascript">
function submit() {
document.getElementById("ctl00_ContentPlaceHolder1_btnPurchase").value = "Processing";
};
</script>
My goal is to change the buttons text to purchasing onclick if the form passes validation, and then in my code behind it will change back to the original value once the form posts back.
I ran across this solution which works 100% perfect. I'm using the script manager with update panels...
<script type="text/javascript">
// Get a reference to the PageRequestManager.
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Using that prm reference, hook _initializeRequest
// and _endRequest, to run our code at the begin and end
// of any async postbacks that occur.
prm.add_initializeRequest(InitializeRequest);
// Executed anytime an async postback occurs.
function InitializeRequest(sender, args) {
// Get a reference to the element that raised the postback,
// and disables it.
$get(args._postBackElement.id).disabled = true;
$get(args._postBackElement.id).value = "Processing...";
}
// Executed when the async postback completes.
function EndRequest(sender, args) {
// Get a reference to the element that raised the postback
// which is completing, and enable it.
$get(args._postBackElement.id).disabled = false;
$get(args._postBackElement.id).value = "Purchase";
}
</script>
I just asked a very similar question (which was answered):
ASP.NET Custom Button Control - How to Override OnClientClick But Preserve Existing Behaviour?
Essentially you need to preserve the existing behaviour of the submit button (__doPostBack). You do this with Page.GetPostBackEventReference(myButton).
However with validation it's more difficult, so you'll need to do page validation inline (Page.Validate()) or create a custom control like i did and override the OnClientClick and PostBackOptions members.
Custom control is better, as i can now just drop this control on any page i want this behaviour.
You could do the same and expose a public property:
public string loadingText {get; set;}
Which could be used to customise the loading text on each page.
You basically need to set the onclick attribute to do the following:
onclick = "if (Page_Validate()) this.text = 'Processing';{0} else return false;"
{0} should be the regular postback action, retrieved from Page.GetPostBackEventReference.
The resulting logic will be: on click, validate the page, it it succeeds, change the text and postback, if it fails, return false - which will show the validation on the page.
Have the button set to default text "Submit" in the HTML, then wrap the above logic in !Page.IsPostBack so it will reset the text on form submit.
Hope that helps.