ASP.net - Button - Javascript Confirm dialog - execute SOME server-side code? - javascript

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;
}

Related

jsf validation before js and js before bean action

JSF / PrimeFaces 3.5
I need when clicking on p:commandButton to check the validation first of all (input text required=true)
if validationFail == false then
Call the popup dialog from js :
else
show requiredMessage from inputText (this field is mandatory...)
I have tried with oncomplete but it calls my bean and after the js popup dialog. I dont want it.
I need in this order : click p:button -> check validation -> if not fails -> show primefaces dialog.
if fails after validation-> render message
My xhtml :
<p:commandButton id="btnSalvar"
value="abc"
action="#{notaFiscalManagedBean.salvar}"
oncomplete="if (args.validationFailed) return true; else return showPF_DiagBox()"
in my showPF dialog I call bean method. if OK clicked by user.
It is better to user RequestContext of primefaces which allows user to execute javascript which is set from managed bean. You can use it by modifying your method at #{notaFiscalManagedBean.salvar} as shown below.
public String salvar(){
boolean valid=true;
//Do your validation here
if(valid){
RequestContext.getCurrentInstance().execute("showPF_DiagBox()");
}
}
If you want to do the validation on client side before submitting the request to the server then just do the following change in your code,
<p:commandButton id="btnSalvar"
value="abc"
action="#{notaFiscalManagedBean.salvar}"
onclick="if(validationFailed()){return false}"
oncomplete="showPF_DiagBox()"/>
Also write down a javascript function to do validations
function validationFailed(){
//Check various conditions based on component validations and return whether validatoin failed or not
}
Try this:
<p:commandButton id="btnSalvar"
value="abc"
action="#{notaFiscalManagedBean.salvar}"
update="#form"
render="#form"/>
By adding 'render' and 'update' attributed your form will have to reload, and then process all the validations inside of it's form.
Hope this can help you, good luck!
In my oncomplete commandButton I got what I wanted getting from #BalusC answer (How to find indication of a Validation error (required="true") while doing ajax command) and #Tuukka Mustonen (JSF 2.0 AJAX: Call a bean method from javascript with jsf.ajax.request (or some other way)) and making some adjustments to fit my needs.
This way, if there are any validation errors or any converters do be validated, they are rendered at screen first of all. If there are not validation errors so I execute my js function and inside it I fire my bean method if needed.
thanks for everybody ! :)

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");
}

change text of asp.net button with javascript

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.

launch two actions in one button ASP.NET

I'm developing a comment page in asp.net, this my page :
<form action="#">
<p><textarea id="textArea" rows="5" cols="30"></textarea></p>
<input type="submit" value="Submit" />
</form>
<p>Add some comments to the page</p>
And this is my javascript code :
window.onload = initAll;
function initAll() {
document.getElementsByTagName("form")[0].onsubmit = addNode;
}
function addNode() {
var inText = document.getElementById("textArea").value;
var newText = document.createTextNode(inText);
var newGraf = document.createElement("p");
newGraf.appendChild(newText);
var docBody = document.getElementsByTagName("body")[0];
docBody.appendChild(newGraf);
return false;
}
Until then, everything is fine, but I want when the user clicks the submit button, the button will trigger another action that will save the comment in the database.
How can I do this thing ?
Why don't you have a wrapper and still make it one function?
The addNode could have code to do both maybe based on something in the form?
You could have a submit function that wraps the addNode and addComment.
eg:
function handleSubmit()
{
addNode();
addComment();
return false;
}
EDIT: Since you want to call server code you have a couple of options. You can do it all via ajax and you would just need to implement the addComment function to call a server side event. See this article if you need help doing so:
http://www.dexign.net/post/2008/07/16/jQuery-To-Call-ASPNET-Page-Methods-and-Web-Services.aspx
The easiest way would be to change your button to an ASP.NET button and then implement the button click event which would call your server side method although this would cause a full page refresh.
A hybrid of the two, which is very easy to implement, would be to use an UpdatePanel. When you clicked your button you would get the look and feel of the AJAX solution but only need to know how to do all the server side code and let the UpdatePanel handle all the AJAX work. This method is a little heavier than just doing a raw ajax call but it is significantly more simple to do.
You can read up on UpdatePanels at: http://msdn.microsoft.com/en-us/library/bb399001.aspx
Instead of using an HTML input tag, use asp:Button, like so:
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" />
What this says is, use a Button that calls the "btnSubmit_Click" method whenever it is clicked on, and run this on the server (not on the client machine).
Then in your code-behind (you do have a code-behind, right? e.g., nameOfPage.aspx.cs), you can add the aforementioned btnSubmit_Click method:
protected void btnSubmit_Click(object sender, System.EventArgs e) {
// interact with database here.
}

How to programmatically change the OnClientClick event and call it?

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.

Categories