How to get confirmation of an action in a web page? - javascript

On an ASPX page I have a "Delete" button that is wired up to a method that calls for the current record to be deleted. The button is wired up in this way:
<asp:Button ID="btnDeleteUser" runat="server" Text="Delete" OnClick="btnDeleteUser_Click" />
protected void btnDeleteUser_Click(object sender, EventArgs e)
{
DeleteUser();
}
I want to interrupt the delete action with a confirmation dialog, and if it is confirmed then the delete method is called. Presumably I would put an OnClientClick method in there.
OnClientClick="confirmDelete();"
<script type="text/javascript">
function confirmDelete(){
var msg = "This will delete this AR Contact. Are you sure you wish to do this.";
if (confirm(msg)){
// Do something here that causes the delete method on the server to be called
}
}
</script>
This raises an OK/Cancel dialog, and clicking Cancel obviously leads to nothing happening, but what if OK is clicked? How is the Delete method on the server to be called? I suppose that I could do a window.open onto a page that did the actual delete, and I can do that, but is there a way to submit to the server-side delete method from JavaScript?

<script type="text/javascript">
function confirmDelete(){
var msg = "This will delete this AR Contact. Are you sure you wish to do this?";
return confirm(msg);
}
</script>
And make sure this attribute is on your button.
OnClientClick="return confirmDelete();"
Confirm returns true if the user clicks yes. It returns false if the user hits no. So you just return that, and it will automatically proceed to the server side function if the client side function returned true.

The javascript confirm will not call the server method if the user cancels. If the user clicks ok, the javascript confirm would allow the button to send its request to the server.
You don't need to worry about opening a new page, etc.
Sample 1:
<asp:Button ID="btnDeleteUser" runat="server" Text="Delete" OnClick="btnDeleteUser_Click"
OnClientClick="return confirm('This will delete this AR Contact. Are you sure you wish to do this?');" />
And leave your server-side code the same.
protected void btnDeleteUser_Click(object sender, EventArgs e)
{
DeleteUser();
}
Sample 2:
If you have multiple items that can raise the same confirmation message, go ahead and do it the way you had it. However, it would look like this:
<asp:Button ID="btnDeleteUser" runat="server" Text="Delete" OnClick="btnDeleteUser_Click"
OnClientClick="return confirmDelete();" />
And the javascript:
<script type="text/javascript">
function confirmDelete(){
var msg = "This will delete this AR Contact. Are you sure you wish to do this.";
return confirm(msg);
}
</script>
When you return the confirm's result, it should be seen by ASP.NET's postback javascript. If confirm or your confirmDelete method returns false, then the postback should be skipped.

Related

C# method skipping over java script call

I have an ASP button that has an event listener attached to it. When pressed it calls the C# method and executes whatever code I may have within it.
I have a javascript function I want to call when the listener first executes. However, C# completely skips over the function call and moves on to the lines below it.
Here's the question: Why is it skipping over the call? And when I isolate just the call, ( have nothing in the method other than the call) IT WORKS. The very second I put another line of code below it, it stops being called. Any help would be greatly appreciated.
Here is the ASP button.
<asp:Button ID="crapJim" runat="server" Text="RateTest" OnClick="crapJim_Click"/>
And here is the C# Method
protected void crapJim_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "getSessionName()", true);
/* ClientScript.RegisterStartupScript(GetType(), "hwa", "getSessionName();", true);*/
string s = hfRaterName.Value;
Console.Write(s);
string stop = "";
}
Currently have the ClientScript commented out and trying the ScriptManager. Both work individually, but not when other code is with it. What I mean by that is:
protected void crapJim_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "getSessionName()", true);
}
Just this alone will work, but any other code with it, it will no longer fire. C# skips over it.
Oh and here is the Javascript code I am using.
function getSessionName() {
var hfRaterName = prompt("Please enter your session name");
hfRaterName.value = hfRaterName;
}
There's an easier way, if you don't have to use RegisterStartupScript.
.aspx:
// OnClientClick will call your javascript function first, then the code behind.
<asp:Button ID="btnPrompt" runat="server" Text="Prompt"
OnClientClick="doPrompt();"
OnClick="btnPrompt_Click" />
<br />
<asp:Label ID="lblPromptResult" runat="server"></asp:Label>
<br />
<asp:HiddenField ID="hfPrompt" runat="server" />
<br />
<script>
function doPrompt() {
document.getElementById("hfPrompt").value =
prompt("Please enter your session name");
}
</script>
Code behind:
protected void btnPrompt_Click(object sender, EventArgs e)
{
lblPromptResult.Text = hfPrompt.Value;
}
In the case anyone else comes across this same problem. I took wazz's advice and used the OnclientClick along with Onclick. Executing the Javascript first rather than having the C# call the Javascript.
//This is the HiddenField used to capture the users identified session name
//which I then store in a DB and use in a few other related pages.
<asp:HiddenField ID="HiddenField1" ClientIDMode="Static" runat="server" />
//This is the ASP button used to call both the Javascript and C# code behind
<asp:Button ID="btnRateBeazely" ClientIDMode="Static" runat="server" CssClass="btnbig" Text="Rate Beazley" OnClick="btnRateBeazely_Click" OnClientClick="getSessionName();" />
//The Javascript is simple, but does exactly what I want it to. DB has character
//limit to 50 so I ensure the user can't input higher than that. Assign the input
//to the hiddenfield ID and off we go.
function getSessionName() {
var SessionSet = prompt("Please enter your session name");
while (SessionSet.length > 49) {
alert("You have too many characters. Please enter again.")
var SessionSet = prompt("Please reenter your session name");
}
document.getElementById("HiddenField1").value = SessionSet;
}
//In the code behind I just assign a new string variable to the hidden field value

Send Command.Value via Javascript to codebehind

I am fairly new to ASP.Net and I am stuck.
If my Hyperlink is clicked a Command.Value should be sent to the server. After getting that Command.Value the code behind should check if it is right and redirect to a specific site otherwise just reload the page.
Here is my Hyperlink:
<asp:HyperLink
ID="Link"
runat="server"
Visible="true"
NavigateUrl="javascript:document.FormServer.Command.value =
'test';document.FormServer.submit();"
>Test!!</asp:HyperLink>
First of all I want to ask if my Hyperlink is right. Furthermore I am a bit stuck on the code behind regarding where I need to insert my If statement.
I believe it's much easier to send a parameter by GET in the url of your link. But if for any reason you want to do it by post and using javascript then try this.
Web form: param1 is a hidden field which value will be set using Javascript. When the form is submitted the hidden field is posted with the form.
<form id="FormServer" runat="server" >
<input type="text" id="param1" name="param1" style="display:none;" />
<div>
<asp:HyperLink
ID="Link"
runat="server"
Visible="true"
NavigateUrl="javascript:document.getElementById('param1').value = 'test';document.forms['FormServer'].submit();"
>Test!!</asp:HyperLink>
</div>
</form>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
string param1Value = Request["param1"];
if (param1Value == "test")
Response.Redirect("~/Default.aspx");
else if(param1Value == "lost")
Response.Redirect("http://www.google.com");
}
In the code behind it might be useful to check this.IsPostBack. That tells you why the page is being loaded. If it's because the link was clicked then IsPostBack will be true.

how to disable button after first click in javascript

I am new to C#. I have a save button inside InsertItemTemplate. I have used the following code to disable the button after first click in java script but its not even working for the first click please help me.
<asp:ImageButton ID="imgbtnSave" runat="server" CommandName="Add" CausesValidation="true" OnClientClick="this.disabled='true';return true;" />
You are modifying the "disabled" property of the DOM object on the browser, but the button will do a post back to the server when it's clicked, so any change to the DOM will be lost.
On the function where you handle the command "Add" in your server code you must retrieve the button from the InsertItemTemplate and set its "Enabled" property to false, that will disable the control from the server side.
If you want to avoid multiple clicks while the page has not been reloaded then you need a client function to avoid this, something like this:
<asp:ImageButton ID="imgbtnSave" runat="server" CommandName="Add" CausesValidation="true" OnClientClick="return checkEnabled(this);" />
<!-- somewhere in your page -->
<script>
function checkEnabled(item)
{
if(item.disabled != 'true')
{
item.disabled = 'true';
return true;
}
return false;
}
</script>

How to fire a button click event from JavaScript in ASP.NET

How do I fire a server side button click event from JavaScript?
I tried like this:
document.getElementById("<%= ButtonID.ClientID %>").click();
But no use. How can I do it?
You can just place this line in a JavaScript function:
__doPostBack('btnSubmit','OnClick');
Or do something like this:
$('#btnSubmit').trigger('click');
var clickButton = document.getElementById("<%= btnClearSession.ClientID %>");
clickButton.click();
That solution works for me, but remember it wont work if your asp button has
Visible="False"
To hide button that should be triggered with that script you should hide it with <div hidden></div>
I used the below JavaScript code and it works...
var clickButton = document.getElementById("<%= btnClearSession.ClientID %>");
clickButton.click();
None of the solutions posted here would work for me, this was my eventual solution to the problem.
// In Server Side code
protected void Page_Load(object sender, EventArgs e)
{
Page.GetPostBackEventReference(hiddenButton);
}
// Javascript
function SetSaved() {
__doPostBack("<%= hiddenButton.UniqueID %>", "OnClick");
}
// ASP
<asp:Button ID="hiddenButton" runat="server" OnClick="btnSaveGroup_Click" Visible="false"/>
I lived this problem in two days and suddenly I realized it that I am using this click method(for asp button) in a submit button(in html submit button) javascript method...
I mean ->
I have an html submit button and an asp button like these:
<input type="submit" value="Siparişi Gönder" onclick="SendEmail()" />
<asp:Button ID="sendEmailButton" runat="server" Text="Gönder" OnClick="SendToEmail" Visible="True"></asp:Button>
SendToEmail() is a server side method in Default.aspx
SendEmail() is a javascript method like this:
<script type="text/javascript" lang="javascript">
function SendEmail() {
document.getElementById('<%= sendEmailButton.UniqueID %>').click();
alert("Your message is sending...");
}
</script>
And this "document.getElementById('<%= sendEmailButton.UniqueID %>').click();" method did not work in just Crome. It was working in IE and Firefox.
Then I tried and tried a lot of ways for executing "SendToEmail()" method in Crome.
Then suddenly I changed html submit button --> just html button like this and now it is working:
<input type="button" value="Siparişi Gönder" onclick="SendEmail()" />
Have a nice days...
I can make things work this way:
inside javascript junction that is executed by the html button:
document.getElementById("<%= Button2.ClientID %>").click();
ASP button inside div:
<div id="submitBtn" style="display: none;">
<asp:Button ID="Button2" runat="server" Text="Submit" ValidationGroup="AllValidators" OnClick="Button2_Click" />
</div>
Everything runs from the .cs file except that the code below doesn't execute. There is no message box and redirect to the same page (refresh all boxes):
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
cmd2.CommandText = insertSuperRoster;
cmd2.Connection = con;
cmd2.ExecuteNonQuery();
string url = "VaccineRefusal.aspx";
ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Data Inserted Successfully!');window.location.href = '" + url + "';", true);
}
Any ideas why these lines won't execute?
You can fill a hidden field from your JavaScript code and do an explicit postback from JavaScript. Then from the server side, check that hiddenfield and do whatever necessary.
document.FormName.btnSubmit.click();
works for me. Enjoy.
$("#"+document.getElementById("<%= ButtonID.ClientID %>")).trigger("click");
The issue I had was the validation group that was not specified.
I added ValidationGroup="none" as per below and it worked.
<asp:Button ID="BtnQuickSearch" runat="server" Text="Search"
OnClick="BtnQuickSearch_Click" ValidationGroup="none" />
I must mention that I had 2 other forms with buttons on the page, both had their own validation groups specified. This button had did not have a validation group specified and the onclick event simply did not fire.

How to...Add Client Side function to button that postsback?

I have a button that closes a modal dialog box on an ASP.NET Ajax form. How do a add a client side function to be called on the same button click?
currently firebug has this for the onclick
javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$DefaultContent$btnPaymentActionDetailClose", "", true, "", "", false, false))
can I just add a click handler with jQuery? I don't want to wipe out the postback as it is necessary for the forms functionality.
Can I use
$("#buttonId").bind("click", function(e){
runAnotherFunction();
});
And not interfere with the existing postback?
Actually truth be told, I want to exec the function when the modal dialog closes. Do ajax control toolkit widgets fire any type of events? I know I can find the behavior and call show and hide. Can I attach my function to exec when modal.hide() is executed?
Thanks for any advice,
~ck in San Diego
Yes, you can definitely have your ASP:Button run Javascript on the client before posting back. It's the OnClientClick property of the webcontrol.
You won't need jQuery for this.
<asp:button id="btn" runat="server" onClientClick="SomeJsFunction()"
onClick="ServerSideMethod()" Text="Hello Button" />
<script language='javascript'>
function SomeJsFunction()
{
alert('hi');
}
</script>
If you're interested controlling whether the postback occurs or not, you could return and check for true/false from the result of your Javascript function.
function SomeJsFunction()
{
var isGood = false;
return isGood;
}
<asp:button id="btn" runat="server" onClientClick="return SomeJsFunction()"
onClick="ServerSideMethod()" Text="Hello Button" />
(thanks to Ralph for the nudge in the comments)

Categories

Resources