I working on an ASP.Net C# application, I wanted to create a Button Control, when user click on the button, a JavaScript confirm popup, then get the Boolean value from the user (Yes/No) to perform further actions in the button onClick event.
my current approach was added OnClientClick and OnClick event in the button, where OnClientClick trigger JavaScript function and the (Yes/No) value is store into HiddenField Control to make use during OnClick event.
It is something like the following code fragments:
function CreatePopup(){
var value = confirm("Do you confirm?");
var hdn1 = document.getElementById('hdn1');
hdn1.Value = value;
}
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" OnClientClick="CreatePopup()"/>
<asp:HiddenField ID="hdn1" runat="server" />
Is there any better approach in order to do this? thank you in advanced.
Change your CreatePopup() function to return a boolean:
function CreatePopup()
{
return confirm("Do you confirm?");
}
And then ensure you return that from the OnClientClick() in the button:
<asp:Button ... OnClientClick="return CreatePopup();" />
Using that method, the OnClick() method will only fire if the OnClientClick() method returns true.
Why do you want to store the value of the JavaScript confirmation in the hidden field? Just simply return false in your JavaScript function when the confirm value is 'no' , to prevent the form from submitting. When cnfirm value is yes, return true to allow the form to be submitted. In your code behind in the button_click method you don't have to check what happened in your JavaScript confirm, since form will never be submitted if the user said no.
Related
How can I check whether a particular button was clicked or not in ASP.NET?
I think I need to perform some operation on Page_Load. This shouldn't be entering to Button_Click event to find. Is there any way that I can find where it was clicked or not on Client Side and take it to Page_Load?
Background: Basically __EVENTTARGET and __EVENTARGUMENT , These two Hidden controls are added to the HTML source, when ever any autopostback attribute is set to true for any of the web control.
The __EVENTTARGET hidden variable will tell the server ,which control actually does the server side event firing so that the framework can fire the server side event for that control.
The __ EVENTARGUMENT variable is used to provide additional event information if needed by the application, which can be accessed in the server.
So we can easily get the control causing postback using:Request.Params.Get("__EVENTTARGET");
PROBLEM:
The method: Request.Params.Get("__EVENTTARGET"); will work for CheckBoxes, DropDownLists, LinkButtons, etc.. but this does not work for Button controls such as Buttons and ImageButtons
The Button controls and ImageButton controls does not call the __doPostBack function. Because of this, the _EVENTTARGET will always be empty. However, other controls uses javascript function __doPostBack to trigger postback.
So, I will suggest to do something as below. Add an OnClientClick property to the buttons. Also, define a hiddenField in your Markup, whose value will contain the actual button causing postback.
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick = "SetSource(this.id)" />
<asp:ImageButton ID="ImageButton1" runat="server"
OnClientClick = "SetSource(this.id)" />
<asp:HiddenField ID="hidSourceID" runat="server" />
On the OnClientClick property of the Button and ImageButton Call the SetSource JavaScript function
<script type = "text/javascript">
function SetSource(SourceID)
{
var hidSourceID =
document.getElementById("<%=hidSourceID.ClientID%>");
hidSourceID.value = SourceID;
}
</script>
Here onwards, you can very easily check in your Page_Load as to which Control caused postback:
if (IsPostBack)
{
string CtrlName;
CtrlName=hidSourceID.Value;
}
I just got the same trouble, have to do some logic judgement in the Page_Load method to treat different event(which button was clicked).
I realize the arm to get the as the following example.
The front end aspx source code(I have many Buttons with IDs F2, F3, F6, F12.
<Button Style="display: none" ID="F2" runat="server" Text="F2:Cancel" OnClientClick="SeiGyo(this)" OnClick="F2_Click" />
<Button Style="display: none" ID="F3" runat="server" Text="F3:Return" OnClientClick="SeiGyo(this)" OnClick="F3_Click" />
<Button Style="display: none" ID="F6" runat="server" Text="F6:Run" OnClientClick="SeiGyo(this)" OnClick="F6_Click" />
<Button Style="display: none" ID="F12" runat="server" Text="F12:Finish" OnClientClick="SeiGyo(this)" OnClick="F12_Click" />
The back end aspx.cs source code, what I need to do is judge which button was clicked when Page_Load was triggered. It seems a little stupid, but works.
In your situation, the button be clicked will be added into dic. I hope that will be helpful to some one.
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach(var id in new string[]{"F2","F3","F6","F12"})
{
foreach (var key in Request.Params.AllKeys)
{
if (key != null && key.ToString().Contains(id))
dic.Add(id, Request[key.ToString()].ToString());
}
}
The UniqueID of the button will be in Request.Form["__EVENTTARGET"]
This question is already answered at: ASP.NET : Check for click event in page_load
You can try using the hidden field. Make the client side event on the OnclientClick event and try setting the value of hidden field, may be true or false depending on the condition.
And on the page load you can check the value of Hiidden field.
function click()
{
// set the hidden field here
}
And on the page load, simply check the value.
if(HiddenFieldName.Value=="true")
{
//perform the action
}
private bool button1WasClicked = false;
private void button1_Click(object sender, EventArgs e)
{
button1WasClicked = true;
}
if ( button1WasClicked== false)
{
//do somthing
}
I have an asp:button called "Delete" and what I want to do is have a JavaScript confirm popup with the options "Yes" and "No". If "Yes" then delete a record from a SQL DB else if "No" then nothing should happen.
<asp:Button runat="server" ID="btnDelete" Text="Delete"
OnClientClick="if(confirm('Delete?'))alert('You chose yes!');else alert('You chose no!')"
OnClick="btnDelete_Click" />
btnDelete_Click contains SQL delete logic.
The problem I am having is that the OnClick method always gets executed. Whether you pick "Yes" or "No" from the JavaScript popup the record gets deleted regardless. It seems to always cause a postback.
Can I somehow get the "Yes" or "No" result into my code behind so I can actually do a simple "if" statement for the delete logic?
Try this, on your javascript do this
var result = Confirm("Are you sure . . . . ");
if(result)
return true;
else
return false;
what it does is if it's true, it should postback your code, else it'd cancel your click.
That should be:
<asp:Button runat="server" ID="btnDeleteSite" Text="Delete" OnClientClick="return confirm('Format Delete?');" OnClick="btnDeleteSite_Click" />
You should ideally put JS event handlers in the script tag, and call them from your OnClientClick event in the button definition. Like so:
<script type="text/javascript">
function ConfirmDelete() {
return confirm("Delete?");
}
</script>
And then in your button's OnClientClick event, you do this:
OnClientClick="return ConfirmDelete()"
This keeps your markup clean and readable, and will also prevent the postback from happening if the user chooses 'No'.
Try with this
<asp:Button runat="server" ID="btnDelete" Text="Delete" OnClientClick="if(confirm('Delete?')){return true;}else {return false;} OnClick="btnDelete_Click" />
When you are using OnClientClick event with JS confirm dialog box at that time you need to return true or false. If it will return True then OnClick(Server side) event will fire otherwise it will not.
I have a button that, when an user clicks on it and some fields are not correct, a message will be displayed. I would like to make that validation with javascript(or maybe someday I will), but I have no idea how to make that. Currently when the user clicks the button, the onclick function on the server side wont be executed.
Just use <asp:Validator tags; there are a number of different types of validators such as required field validators regex validators, etc.
They will validate the data both in client side code as well as server side code (unless you disable the client side check, which you can do).
This is much easier than manually validating the content in javascript and also manually validating it in server side code.
Technically though, to answer your question, when you have an onclick javascript handler for a submit button the return value, as a boolean, indicates whether or not the form should be submitted, so you just need to return false if the data is not valid to not submit the form.
<asp:Button Text="Submit" OnClientClick="return Validate();" />
<script type="text/Javascript">
function Validate()
{
if(requiredFieldAIsMissing) return false;
return true;
}
</script>
How about:
<asp:Button ID="myButton" Text="Click Me!" OnClick="myButton_OnClick" OnClientClick="javascript:confirm('Really?')" />
The OnClientClick property emits the javascript (ahead of the javascript required to handle the postback), and if you return false from that event the rest of the event is cancelled and the postback will not fire.
I think something like below would help you to understand.
HTML:
<asp:textbox id="myText" runat="server" text="Hello" />
<asp:button id="myButton" runat="server" text="Click Me" OnClick="Server_Event" />
ON Page_Load:
//Add onclick with return here
myButton.Attributes.Add("onclick","return ButtonClicked()");
Javascript:
function ButtonClicked(){
var txt = document.getElementById("myText");
if(txt.value != "Hello"){
alert("It is not Hello, I am NOT posting back!");
return false;
} else {
alert("It is Hello, I am posting back!");
return true;
}
}
I have an ASP.NET form that takes input from a user. There's a Submit button on the form and a button called Calc which does a calculation to populate a text field. The problem I'm having is that on the form I have a set of <ASP:REQUIREDFIELDVALIDATOR> validators and when the Calc button is pressed the form gets validated. I don't want the required fields to be validated when the Calc button is pressed, only the Submit button. Any way around this?
Set the CausesValidation property to false.
<asp:Button runat="Server" ... CausesValidation="False" />
Button.CausesValidation (If I remember correctly).
Try putting CausesValidation="false" as a button attribute.
Some sample code:
http://weblogs.asp.net/scottgu/archive/2005/08/04/421647.aspx
ASPX Page:
<asp:Button ID="buttonNew" runat="server" Text="New" CausesValidation="False" />
OR
CodeBehind Page: (.cs)
buttonNew.CausesValidation = false;
Check here to know more about Validated and Validating events for the controls.
Set the button.causesValidation to false.
this link
However, if all it is doing is calculating something based on user input then you shouldn't have it posting back at all. I would recommend using an HTML button and attach some javascript to it to do your work for you and then you won't have this problem.
While designing the button, you can set its property CausesValidation="false" to avoid validation on button click event. It does not allow to validation the server control and perform its click event only
You should use this
UseSubmitBehavior="False"
To disable validation in a specific control
Set the control's CausesValidation property to false.
<asp:Button id="Button3" runat="server"
Text="Cancel" CausesValidation="False">
</asp:Button>
To disable a validation control
Set the validation controls Enabled property to false.
To disable client-side validation
Set the validation controls EnableClientScript property to false.
For More Info
Hi im looking to find out after I do this:
c#
div.Attributes.Add("onclick", "return confirm_delete();");
javascript:
function confirm_delete()
{
if (confirm("Are you sure you want to delete this comment?")==true)
return true;
else
return false;
}
It pops up with a message box with yes and no if I press yes how can I add a function into my c# how can I call it?
If yes go to c# code behind
and add in confirm_delete
if yes was clicked
do this
I need it so when some one clickes yes I can (from code behind in asp.net c#) add in a method to delete from mysql database.
Just dont know how I refrence to the javascript
public static string confirm_delete()
{
return something (dont know how to)
}
How about this add a button with the clientside click event instead of adding it in the code behind. Check to see if the popup returns true. If you return false it should prevent the server side event from firing.
<asp:Button ID="btn" OnClientClick="if(confirm_delete()){
/* post back*/
}else{
return false;
};" OnClick="btnDelete_Click" runat="server" Text="delete"/>
protected void btnDelete_Click(object sender, EventArgs e)
{
//run your serverside code if confirm was pressed.
}
Your JavaScript will need to call a page on your server. This is typically accomplished with AJAX and a web service.
This page on MSDN has a good overview of what's involved.
If you're interested in using jQuery, this page has a simple example.
You may be able to use a PageMethod to call your codebehind function, check out the following link for an example
ASP.NET Ajax PageMethods
Wondering why you are using a div? Can't you use asp.net Button / LinkButton and limiting it's postback based on confirm value?
e.g.
<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete"
OnClientClick="return confirm('Are you certain you want to delete this
product?');">
</asp:LinkButton>
Reference.