In my C# code, I have presented a confirm box to the user using the following code:
string confirmMsg = "All the cause data will be permanently removed. Are you sure you want to continue";
ClientScript.RegisterStartupScript(Page.GetType(), "TWCL Issue Mgmt System", "confirm('" + confirmMsg + "');", true);
I am trying to get the answer (YES or No) into a boolean or some other variable so that I can execute other code based on the answer given. So I would like something like this:
bool x = ClientScript.RegisterStartupScript(Page.GetType(), "TWCL Issue Mgmt System", "confirm('" + confirmMsg + "');", true);
if(x)
{
/*Exceute the rest of the code here*/
}
else
{
/*do postback*/
}
Any ideas on how to get the YES/NO answer from the confirm box?
Create a hidden field on the form. Write the answer of the question in the hidden field with some javascript. Read the value of the hidden field in the code behind.
The startup script that you are registering will run when the web page is displayed, before the user has had a chance to interact with it. A confirmation prompt at this time will likely be confusing.
It's more usual to use the OnClientClick property of a button that is doing the postback:
<asp:Button ...
OnClientClick="return confirm('Are you sure?');"
/>
so that the confirmation prompt is only displayed when the user attempts to post.
Related
I want to give user warning with confirm message box if they want to save without uploading image.
Code fires when user click on save button
if (string.IsNullOrEmpty(obj.Image)) {
obj.Image= null;
//Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "alert('Please Upload Image!');", true);
Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "confirm('Are you sure you want to save without uploading images?');", true);
}
Above logic for was for showing confirm box but it doesn't show.
Besides that, how can I trap if user clicked on Yes or No button?
so that i can fire related code accordingly.
Update:
I am able to show confirm box with following code
Page.ClientScript.RegisterStartupScript(this.GetType(), "msgbxConfirm", "confirm('Are you sure?');", true);
But i am not sure how i am going to trap the YES or No event
To handle the result of a confirm popup box - check the return value.
If OK is clicked it will return true, else it will return false.
EG:
if(confirm('test')) {
alert('ok clicked')
} else {
alert('cancel clicked or closed popup')
}
JSFiddle example code in action
EDIT: comments
To resubmit the form if the user clicks OK on the confirm dialog something like this is what you need:
Codebehind:
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"msgbxConfirm",
"doConfirm();",
true
);
aspx page:
<script type=text/javascript>
function doConfirm() {
if(confirm('Are you sure?') {
document.getElementById(<id_of_form_submit_button>).click();
}
}
</script>
One thing i am adding here, you can not get the confirm result in server side code, you have to write that code in JS side. So to maintain it in better manner, you can use following JS in aspx.
function ConfirmAndExecute()
{
if(confirm("Are you sure?"))
{
OnConfirm();
}
else
alert("you missed !")
}
function OnConfirm()
{
// JS Code to handle post confirm operation
}
And in server side, page_load, use following.
Page.ClientScript.RegisterStartupScript(this.GetType(), "msgbxConfirm", "ConfirmAndExecute();", true);
You could also just add an onclick client script event handle to prevent submission of the form unless the confirmation is true so you don't have to deal with the script registration. Just add the code below into your asp:button definition
<asp:Button id="btnSave" Text="Save" runat="server" OnClientClick="return confirm('Are you sure?');" />
I am working on asp.net web application.
I have one UpdatePanel and there is table inside table which has data in some TextBoxes.
I have one save button too inside this UpdatePanel
So I want to save this data into Database, when I click Save Button.
This is working fine till now.
But I want to show alert message to User that information saved successfully. I'm using javascript for this purpose, But Javascript is not working.
so is this possible to achieve the desired functionality using javascript, if yes then please guide me Or if there is any other alternative method except this please let me know.
Thanks,
Vivek
If you have update panel use ScriptManager.RegisterClientScriptBlock as below
ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "alert", "alert('Member Registered Sucessfully');", true)
Remember that you can't use Response.Write during an asynchronous postback.
It would be good if you have posted your code here.
Try This Line of Code
Its Definitely work with Update panel.
var message = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize("Bill No. : " + BillNo + " successfully generated.");
var script = string.Format("alert({0});window.location ='ChhallanPrint.aspx';", message);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", script, true);
Try this for popup sweetalert in asp vb.net
Dim message As String = " swal('Added!','Country Added Successfully.', 'success')"
ScriptManager.RegisterClientScriptBlock(TryCast(sender, Control), Me.GetType(), "sweetAlert", message, True)
string message = " swal('"+gelen[2]+"!','Sepete Eklendi.', 'success')";
ScriptManager.RegisterClientScriptBlock(this,this.GetType(), "sweetAlert", message, true);
I'm developing an asp.net application and I need to call a confirm dialog box on the code behind. And after that, I need to get the user's click (if he clicked at OK or Cancel).
If he clicked the OK button of the dialog, I must continue to running the code where I stopped before call the dialog.
To solve this problem I thought in put at the aspx an input of type button, and set it's style to visibility:hide. So, when the users click on the OK button the programm will call this hidden button which calls a method that will continue the job stopped.
I'll post my code, I expect it might help.
The code below is on my code behind, and it calls the confirm dialog.
System.Web.UI.
ScriptManager.RegisterClientScriptBlock(this, GetType(), "__Mensagem", "if (confirm('" + CustomMessage + "')){document.getElementById(\'<%=btnSave.ClientID%>\').click();}", true);
The code below is on my aspx, it's the "hidden" button.
<input style="visibility:hidden;" id="btnSave" runat="server" onclick="btnSave_Click"/>
I don't know why isn't working. The error that I receive after click on the button OK of the confirm dialog box is the following: Erro em tempo de execução do Microsoft JScript: 'document.getElementByID(...)' é nulo ou não é um objeto
I'm from Brazil so the error is in portuguese, a translation to english it's something like this:
"A runtime error occurred on Microsoft JScript 'document.getElementByID(...)' is null or is not an object"
I give a look at the html code of the page and I notice that the button isn't there.
Maybe it's because I'm using an UpdatePanel, but when I removed it (just for tests, I must use the Update Panel), the same error is showed, and in this time the button were on the page's html code.
A stab in the dark.
In your code-behind have you set btnSave.visible = false;? If so, this would prevent the button from being rendered to the HTML.
Also, is there any reason you're not using the ASP:Button control, rather than a mix of HTML with runat="server"?
Finally, it may help to have type='button' on your <input....
UPDATE
The problem is you're trying to apply an inline tag
document.getElementById(\'<%=btnSave.ClientID%>\')
in your code be <%=btnSave.ClientID%> does not exist yet.
your code will break the moment you put your button inside another server control, as the clientId will become different.
Change the code to this:
document.getElementById('" + btnSave.ClientID + "')
and it will work, regardless of where you have the button.
Once your page is rendered in browser, right click on it, and say "view Source". check the HTML and try to find your hidden button, if you find it, use its id in your statement getElementById(\'<%=btnSave.ClientID%>\') . If you dont find your button, then probably you have set its visibility to false from your code-behind somewhere, remove that, follow the above process again and you should be ok.
I solved the problem replacing the part
document.getElementById(\'<%=btnSave.ClientID%>\').click();
by
$(\"#ctl00_body_btnSave\").click();
I also replace the input element by an asp:Button.
Give a look how my code is on my code behind now:
System.Web.UI.
ScriptManager.RegisterClientScriptBlock(this, GetType(), "__Mensagem", "if (confirm('" + CustomMessage+ "')){$(\"#" + btnSave.ClientID + "\").click();}", true);
And on my aspx:
<asp:Button id="btnSave" Width="0px" Text="" runat="server" onclick="btnSave_Click"/>
The use of Widht="0px" and Text="" to hidden the button isn't recommended, but I used because it won't cause me problems. It's recommended the use of a CssClass which make it hide.
So, if the user confirm the operation, the even btnSave_Click is called.
Thanks for all the answers.
I have to show a yes no popup messagebox for a function>
This is what i do for an alert popup>
Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "<script>alert('File Updated');</script>");
This is what i want to do in the code behind:
if (ID != 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Confirm", "<script>confirm('are you sure?');</script>");
if (yes)
{
perform function
}
else
{
return;
}
}
The confirm is not working,,, any suggestions on how to do this
thanks
Edit Portion:
Navigate to a page
Add values to a textbox
Click "Save" Button to add value to database
Ask the user if he is sure he want to do it 'are you sure'?,, the confirm pop up
Now the above confirm box will only happen if the ID is != 0 or else there is no need for a popup.
if he says yes then add to database and show alert popup that values have been enterd in the DB.
if NO then just dont add to Db and just return.
so i get the confirm box like this.. but how can i get what is selected
string scriptString = "<script language='JavaScript'> ";
scriptString += "confirm ('Are you sure you want to Close this period.')";
scriptString += "</script>";
Response.Write(scriptString);
Is there a button you are clicking on to trigger the action? If so, you should add the client events to your web control like so:
<asp:ImageButton runat="server" ID="DeleteUrlImageButton" ImageUrl="~/Images/icon_remove.gif"
OnClick="DeleteUrlImageButton_Clicked"
OnClientClick="return confirm('Are you sure you want to delete?');" />
If the user selects yes, the postback happens as usual. If they select no, the even is cancelled and no postback occurs. This, IMO, is the way to handle it because it prevents any extra server activity if they select no.
Add a linkbutton.
In the OnClientClick add
javascript:return confirm('Are you sure')
This will not launch the postback if they click no. It will launch the postback if they click yes.
Then in then code behind (OnClick) of the button do your server side processing:
(Will only be executed if they click yes)
if (ID != 0)
{
Perform function
}
See the problem here is that, without posting back, you can't get the value of the confirm box. JavaScript is run client-side and until a postback occurs (either via ajax or the regular way), it can't "talk" to your C# file.
What you'll have to do is add a confirm box in JavaScript which, if Yes is clicked, will post back to your Asp.net page and run code either through Ajax or (example) form.submit().
It appears that what you're trying to do is (in a simplified scenario):
Have the user navigate to Page.aspx
Check the value of ID (lets assume
it's a querystring parameter)
If the value of ID is non-zero, prompt
the user to confirm
If they confirm do "something"
The mistake you're making is attempting to handle 2, 3 and 4 alltogether in the code-behind. The script that you emit (by calling RegisterStartupScript) doesn't get executed until the entire page has been rendered back to the user, at which point the code for steps 3 and 4 to check the value of ID and do something will already have been "skipped over"
What you need to do is decide how to separate the work between client-site and server-side as what you're attempting to do just won't work. Without knowing how your page(s) work and where the ID value comes from I can't give a speciic example, but, something like:
Have your page check ID to see if it hits your criteria, if it does, emit the javascript, but with some additional javascript that checks the response to the prompt and causes the page to re-submit but with confirmed=yes added on the querystring
Have your page check the querystring parameter "confirmed" to see if it's yes. If it is, THEN do the work
You can't do it this way. RegisterStartupScript just registers the script to be included when the page is finally rendered. After it is rendered (to HTML) then the html is sent to the browser. So when the user finally sees that popup, your code has long since finished.
EDIT:
See the answer by Mike C.: you need to move that confirm to just before the submit.
Page.ClientScript.RegisterStartupScript will register that script on the client. As far as I can see you are executing the if statement on the server. Could you please specify what confirm is not working mean? Is the alert box displaying but no effect should yes/no is pressed? If so, move the if ... else statement on the client. Anyway, I suggest that you replace RegisterStartupScriptBlock with this code:
ClientScript.RegisterClientScriptBlock
(this.GetType(), "confirm", "alert('do')", true);
If you have a page with an <asp:TextBox TextMode="Password" ... />.
How can you keep the value after a postback?
This is my problem:
At the registration screen of my app you need to enter a password.
Then you click submit, a postback occurs and the password fields are cleared, how can I prevent the password field from clearing?
You require to set it again in page_load or in button click event like this :
string Password = txtPassword.Text;
txtPassword.Attributes.Add("value", Password);
You need to set back the password to the textbox on postback.
txtBox.Attributes["value"] = txtBox.Text;
Best way
dont set input type in aspx page,
set type of input in Pageload in !postback Section
txtPassword.Attributes["type"] = "password";
<input type="password" /> is treated differently than other form controls since it stores sensitive information that is a password of a user. At server side, for every postback the password textbox is force-fully cleared for this reason, should you really need to persist the value in password text-box, set it explicitly as others have mentioned here. But I really don't recommend doing so since it's not a good practice.
I realize this is an old post, but hopefully this will help someone else. I had the same issue on a user setup screen whereby I kept losing the password input during various postbacks. The solution I chose was to place portion of the input screen that posted back into an updatepanel. This solved the problem of the password being blanked out AND didn't present a security risk.
Hope this helps!
Use Jquery to retain your password after postback or submit
$(function () {
$('.txtPassword').val("<%=txtPassword.Value%>");
});
Just add type="password" in asp:textbox and remove Textmode="Password" and no need to write any code in code-behind.