How can I pop up a message box to confirm a delete, from inside a method?
Normally i would just use the following line in my button:
OnClientClick="return confirm('Are you sure you want to delete this comment?');"
However this delete method can also be called by a querystring, so I need the confirm message box functionality in the method, please?
// delete comment method
private void DeleteComment()
{
int commentid = Int32.Parse(Request.QueryString["c"]);
// call our delete method
DB.DeleteComment(commentid);
}
I can't click the button through code, because it doesn't fire the OnClientClick event
btnDelete_Click(null, null);
Regards
Melt
you can try using this
ibtnDelete.Attributes.Add("onClick", "javascript:return confirm('Are you sure you want to delete ?');");
I would recommend doing something like this.
Add a 2nd query string argument to dictate if it is confirmed or not. Definitely add some code to confirm that the user is logged in so that this query string methodology doesn't get hit by a webcrawler or something and accidentally delete all your comments.
// delete comment method
private void DeleteComment()
{
if(Boolean.Parse(Request.QueryString["confirm"])
{
int commentid = Int32.Parse(Request.QueryString["c"]);
// call our delete method
DB.DeleteComment(commentid);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "ConfirmDelete", #"
if(confirm('Are you sure you want to delete this comment?'))
window.location = '[insert delete location with confirm set to true]';
", true);
}
}
sounds like you need to check the query string with javascript and then display your prompt.
Check out this post:
You could modify the method and call it in your body.onload or (jquery) .ready function. The problem then becomes how to let your server side method know the results? You could set up a separate page that handles the delete and call it using jquery ajax post method.
I guess that's my $.02
Related
I'm completely new to working with JavaScript in ASP .NET so bear with me.
Say I have the following:
protected void btnCreateReplication_Click(object sender, EventArgs e)
{
try
{
doSomething();
}
catch (Exception ex)
{
//How do I display the error? I know if I were in WinForms, I could just do this:
MessageBox.Show(ex.Message);
}
}
First question:
Should I put all of my JavaScript code in a .js file in my ASP .NET solution?
If so, how do I call an alert message from the .js file?
If not, how do I call an alert message instead of the MessageBox.Show?
You'll have to use the Page.ClientScript.RegisterClientScriptBlock method.
string script = "alert('We had an error')";
Page.ClientScript.RegisterClientScriptBlock(GetType(),
"myErrorKey", script, true);
RegisterClientScriptBlock takes a type, a key to see if the script block is already registered, the script, and a boolean indicating whether the method should add the script tags, or if you're string script variable already includes them.
as Dave said, using the tScript.RegisterClientScriptBlock method, you can inject the javascript into your page and have it run.
If you want to make the alert a bit more complex, it is cleaner to use a StringBuilder to set up the script.
Here, a link! http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx
Another helpful way to show JavaScript alerts would be to use OnClientClick in .ASPX page. This is similar to OnClick for ASP Classic if you are familiar with ASP.
OnClientClick="alert('Are you sure you want to delete this user?');"
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
This may not be helpful for you for above code but can use to show other simple alerts.
I'm writing an IE extension using mshtml. Is there a way to get the text from the recent alert displayed to the user (via C# or javascript)?
Thanks in advance.
If you can hijack/inject/exec any JS in your websites, you could just overwrite the alert method with a custom one, which calls the original one inside :) Something like this:
// let's save the alert first
var _super_original_alert = window.alert;
// and now we overwrite it
window.alert = function(s){
// do something with the received string
// i will just log it, but you might want to send the string via
// ajax/jsonp to a remote server
console.log(s)
// call the original intended alert
_super_original_alert(s)
}
It's not nice, but could do the trick.
I am trying to get user confirmation from c# code behind file, to confirm if user wants to overwrite the existing file on server of cancel the operation but so far no luck.
this is my code :
if (File.Exists(filePath))
{
string alertMsg = #"confirm('A File already exists with the same name. \n Would you like to overwrite the existing file ?');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Test", alertMsg, true);
}
else
{
fuPSD.SaveAs(filePath);
}
any help would be highly appreciated.
That code will pop up the message if the file exists and save it if it doesn't.
But you will need to take some action on the confirm dialog result on the client side and either trigger a postback or some other server call to perform the operation in the case of the override.
The problem is that your JavaScript registration will ask the user to confirm to overwrite the file after the next page loads. This then poses the issue of telling whether the user confirmed or denied from the server since you're confirm with be client side.
In the past I've used a hidden field to toggle true/false to show a popup from the server side. This gives me the ability to wire up the events to a delegate on the code behind(I.e make my own confirm box with my own buttons). You can still do this without it by I found that it leads to a lot of messy and hard to follow script like callin __doPostback manually.
something like this :
create
<asp:hiddenField id="hf" />* in the aspx file
also put on the JS location a Declaration :
var answer=null;
back to server :
string alertMsg = #"if (confirm('A File already exists with the same name. \n Would you like to overwrite the existing file ?')==true) answer='1'; else answer='0';";
now on the server side :
read :
hf.value
I am trying to keep track of prints that are made for a page. The page has Print this page link. And the code for it is like below: This is written in .cs file as there are many conditions for displaying this. And i am appending here using String Builder.
sbOutput.AppendFormat("<td align=\"right\" valign=\"bottom\"><div style =\"float:right;text-align:right; valign:bottom;width:200px\"class=\"print_button notPrinted\"><a class=\"notPrinted\" href=\"#\" onclick=\"window.print();\">PRINT THIS COUPON </a><img src=\"images/print-icon-34x34.gif\" class=\"notPrinted\" align=\"absmiddle\" /></div> </td></tr></table>", couponid, Userid, locationid);
Do i have to use onclientclick or something else??
Thanks so much in advance.
Good option would be to write a Javascript function to enable Ajax call, so that you can send a request to server to record the print coomand.
PRINT THIS COUPON
function RecordPrint()
{
// Make a AJAX Call to your server Page to record Print Command.
// printRecorded : success from server
If(printRecorded)
{
window.print();
}
return false;
}
Hope that helps.
since you seem to print on the client side only, you could do
PRINT THIS COUPON
On the server side, implement the counter.aspx page to just count the request and quit silently. Make sure, the window.print() will return true - otherwise the link is not executed.
I am trying to fix some bugs in a product I inherited, and I have this snippet of javascript that is supposed to hilight a couple of boxes and pop up a confirm box. What currently happens is I see the boxes change color and there is a 5 or so second delay, then it's as if the missing confirm just accepts itself. Does anyone smarter than I see anything amiss in this code?
function lastCheckInv() {
document.getElementById("ctl00$ContentPlaceHolderMain$INDet$txtInvNumber").style.background = "yellow";
document.getElementById("ctl00$ContentPlaceHolderMain$INDet$txtInvNumber").focus();
document.getElementById("ctl00_ContentPlaceHolderMain_INDet_AddCharges").style.background = "yellow";
document.getElementById("ctl00_ContentPlaceHolderMain_INDet_lblFreight").style.background = "yellow";
bRetVal = confirm("Are you sure the information associated with this invoice is correct?");
return bRetVal;
}
The only thing I can think of is if one of the lines before the confirm is throwing an exception and you're never actually getting to the confirm.
If you're using IE, make sure script debugging is enabled. If you're using Firefox, install the Firebug add-on and enable it for your website.
Or, for very primitive debugging, just put alerts after each statement and figure out where it's bombing.
You should use the following method to reference your controls from JavaScript:
document.getElementById(<%= txtInvNumber.ClientID %>).style.background = "yellow"
If that doesn't help, try setting a breakpoint in your JavaScript and stepping through it to see where it's failing.
This test script ran fine for me in IE, Firefox, and Opera. So there doesn't seem to be anything wrong with your basic syntax. The problem is either in the ID's (which doesn't fit with the fact that it acts as if confirmed after 5 seconds) or in some other conflicting JavaScript on the page. It will be difficult to help you without seeing more of the page.
<script language="javascript">
function lastCheckInv() {
document.getElementById("test1").style.background = "yellow";
document.getElementById("test1").focus();
document.getElementById("test2").style.background = "yellow";
document.getElementById("test3").style.background = "yellow";
bRetVal = confirm("Are you sure?");
return bRetVal;
}
</script>
<form method="get" onsubmit="return lastCheckInv();">
<input id="test1" name="test1" value="Hello">
<input id="test2" name="test2" value="Hi">
<input id="test3" name="test3" value="Bye">
<input type="submit" name="Save" value="Save">
</form>
A few thoughts: Could be the .focus() call is hiding your confirm behind the page? Or could it be that one of your control id's is not correct causing, the .style.background references to fail?
You should set the focus after showing the confirm box, otherwise the confirm box will grab focus away, making that line meaningless.
Don't hard-code ASP.Net id's like that. While they typically are consistent, a future version of ASP.net won't guarantee the same scheme, meaning your setting yourself up for pain when it comes time to update this code at some point in the future. Use the server-side .ClientID property for the controls to write those values into the javascript somewhere as variables that you can reference.
Update:
Based on your comment to another response, this code will result in a postback if the function returns true. In that case, there's not point in running the .focus() line at all unless you are going to return false.
I do not like accesing objects directly by
document.getElementById("ctl00_ContentPlaceHolderMain_INDet_lblFreight").style.background = "yellow";
If the object is not returned JavaScript will error out. I prefer the method of
var obj = document.getElementById("ctl00_ContentPlaceHolderMain_INDet_lblFreight");
if(obj)
{
obj.style.background = "yellow";
}
My guess is you are trying to access an object that is not on the DOM, so it never gets to the confirm call.
It might be worth checking that the elements actually exist. Also,try delaying the focus until after the confirm():
function lastCheckInv() {
var myObjs,bRetVal;
myObjs=[
"ctl00_ContentPlaceHolderMain_INDet_AddCharges",
"ctl00_ContentPlaceHolderMain_INDet_lblFreight",
"ctl00$ContentPlaceHolderMain$INDet$txtInvNumber"
];
bRetVal = confirm("Are you sure the information associated with this invoice is correct?");
for (var i=0, j=myObjs.length, myElement; i<j; i++){
myElement=document.getElementById(myObjs[i]);
if (!myElement){
// this element is missing
continue;
}
else {
// apply colour
myElement.style.background = "yellow";
// focus the last object in the array
if (i == (j-1) ){
myObj.focus();
}
}
}
return bRetVal;
}
function lastCheckInv()
{
document.getElementById("ctl00_ContentPlaceHolderMain_INDet_txtInvNumber").style.background = "yellow";
document.getElementById("ctl00_ContentPlaceHolderMain_INDet_txtInvNumber").focus();
document.getElementById("ctl00_ContentPlaceHolderMain_INDet_AddCharges").style.background = "yellow";
document.getElementById("ctl00_ContentPlaceHolderMain_INDet_lblFreight").style.background = "yellow";
return confirm("Are you sure the information associated with this invoice is correct?");
}
The first two lines in your function are wrong, $ are in the UniqueID of an ASP.Net Control.
On Clientside you have to use the ClientID, replace $ with _ .
If you are sure that the Controls exists, the
code above might work.
Is bRetVal actually declared anywhere?
If not, "var bRetVal = confirm...." is a friendly way of telling jscript that it is a variable.