Javascript confirm box blocks background - c#

I have a button in a GridView, and when it is clicked it triggers the
protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
event. In there I have some logic and at the end I am registering some javascript that generates a pop up. The issue I am having is that for the confirm pop up when it comes up. It shows a blank screen on the background and when I click cancel it shows it back again, otherwise it navigates to another page... But while the box is up the background is white.
I need to make it so that it shows like the "Alert" pop up that still shows the website in the background. Please note I can only make this work with these pop ups as they are used throughout the website ("not confirm ones"). This is the first confirm box I have had to add but there are many Alerts on other pages. So would not like to change them as it will be too much work (150+ pages website).
Thank you

It looks like the page isn't getting a chance to render before the alert box shows up. Hook up the code that displays the JavaScript alert to something like the body.onload event; this will wait for the page to finish its initial load before displaying the alert.
Page.ClientScript.RegisterClientScriptBlock(
this.GetType(),
"key",
#"
function Redirect() {
location.href = 'shoppingCart.aspx';
}
function showAlert() {
if (confirm('***Message truncated***.') == true){
Redirect();
};
}
// If you're using JQuery, you could do something like this, otherwise you
// would need to add the function call to the HTML body tag's onload attribute.
// There are other alternatives, see:
// http://stackoverflow.com/questions/1235985/attach-a-body-onload-event-with-js
$(document).ready(function() {
showAlert();
});
", true);

Related

Use Ajax to update progress of process running in codebehind

This is a followup on a question I asked earlier.
Update a Web Page as a Process Runs
I want the webpage to display what stage the process is running using Ajax. After each step in the code behind, a file is overwritten with some text indicating what just happened. I want the webpage to periodically send a request for that file and display its contents using either setInterval or setTimeout. Once the button is pressed, the webpage starts its request cycle and the server begins its time consuming operation.
What I have now...
Script for periodic requests:
<script type="text/javascript">
var d = setInterval("Check()", 3000);
function Check() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
alert("get chrome");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
document.getElementById("s").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "temp/test.txt", true);
xmlhttp.send();
}
/*$(document).ready(function () {
$("#uploadbutton").click(Check());
});*/
</script>
Currently Check() starts running as soon as the page loads. I would like it to only be called once the click event happens. If I define the Check() inside the click event, it doesn't recognize the setInterval and will only check if I click the button again. This isn't a huge problem as I think it will be ok to have the script running. It will just display a "not searching" string. Unfortunately as the file gets updated (and I checked that it was) the page does not display the contents as it gets the response. It just remains the same, then once the codebehind finishes, it resets to the default setting. Can anyone tell me why the page isn't updating?
edit: forgot to mention that the click event has an onclick assigned to the C# codebehind that does the long function. I don't know if I can have the javascript Ajax function running and the C# codebehind going too. The Ajax calls have async = true, but the script part isn't running parallel to codebehind right?
edit again: I changed the script to count upwards. I expected it to continue to count while the codebehind did its thing, but once you hit the button it stops. Once the codebehind finishes it restarts the count. Why doesn't the counting keep going? I expect it to restart once the codebehind is finished, but I thought it would keep counting.
setInterval("Check()", 3000); should be called on the button click event. Don't invoke Click() directly on the button click event, just invoke the setInterval("Check()", 3000); and it will invoke Click() for you.

Implementing javascript confirm box in code behind on drop down box's selected index change event firing

Inside my boxLang_OnSelectedIndexChanged() event I got this :-
if (txtbox1.Text != "" && txtbox2.Text != "")
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "confirm", "confirm('Changing the language will clear the text in the textboxes. Click OK to proceed.');", true);
txtbox1.Text = "";
txtbox2.Text = "";
}
Now what is happening is that. When I select a different item from the drop down list this confirm box does show up BUT it first clears the content of the text boxes and then this confirm box appears. What I want is that the textboxes content should be cleared ONLY when OK is clicked.
What am I doing wrong? Please help.Thanks.
edit
#jgauffin
** I typed return where you have. Now what is happening is that its just clearing the textboxes right away..didn't even show the confirm box this time! Whats wrong now?? Please reply..thnx**
edit 2
I tried as follows:-
Inside my BindDropDown() method I added :-
dropdownbox1.Attributes.Add("onChange","DisplayConfirmation()");
then in my aspx page I have added the following script as follows:-
<script type="css/javascript">
function DisplayConfirmation() {
if (confirm('Changing the language will clear the text in the textboxes. Click OK to proceed.')) {
__doPostback('dropdownbox1','');
}
}
</script>
This function is not getting called when drop down's selected index is changed. What's wrong?
edit 3:-
ok I changed the line of code as follows:-
dropdownbox1.Attributes.Add("onchange", "javascript:return DisplayConfirmation()");
Still wont work. I am new to JavaScript and all so having problems. Help will be much appreciated.
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "confirm", "return confirm('Changing the language will clear the text in the textboxes. Click OK to proceed.');", true);
return is needed to break the process on cancel.
That's not going to work. You're posting back to the server, then registering the javascript confirm code, and then clearing content. The javascript confirm box will only actually appear once the page has reloaded, by which time you've already cleared the textbox values. It's like you're confusing clientside and server side programming. Client side code like javascript will only execute when the server has finished doing it's thing and the page is loaded.
What you need is this answer, probably:
DropdownList autoposback after client confirmation

confirm message box

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

JQuery: how to keep a dialog box open after an asp.net postback has occurred

Looking at the other dialog questions, mine seems to be the exact opposite to postback queries. I have a dialog box which opens when a button is clicked. all that is fine. I have attached the dialog to the form and posting to asp.net is fine too, but, my problem is when a postback occurs of course the dialog closes which I do not want to happen as the user may want to post via the dialog function several times. Basically the dialog connects to an asp process that creates a folder, the user may want to create several folders (for image upload) but postback causes the dialog to close, rather abruptly!, and I would rather the user dismissed the dialog when they have finished. Any ideas how I might achieve that? I'm using Jquery and Asp.net C#. I'm fairly new to both c# and Jq so am flummuxed. I've tried this lastly........... Thanks
protected void Page_Load(object sender, System.EventArgs e)
{
if (IsPostBack)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "callme", "$('#opener').click(function(x)", true);
}
}
I'd suggest looking at using an AJAX post to call your 'Create Folder' function, that way you can separate the postback from the currently displayed page and maintain your state there.
You might want to consider using AJAX to post the data from the dialog box. Otherwise, you could check for Page.IsPostback and open the dialog if true.
You could trigger the .click() event on your #opener object on Postback:
<script type="text/javascript">
$(function() {
<% if (Page.IsPostback) { %>
$('#opener').trigger('click');
<% } %>
});
</script>

Button disable function after clicking on it

i have save button in around 150 pages. when ever the user clicks on save button i should disable the button after the click. so that user does not keep clicking on save button again.
protected void Button1_Click(object sender, EventArgs e)
{
// right now once the user clicks the save button
Button1.Enabled = "false"
}
right now i am doing like this. is there any better solution u can provide me to improve codeing here would be great.
thank you
I think the best option to accomplish this is using javascript. If you are using jQuery (which I can even start to recommend enough) then you can put the javascript in your masterpage. You just need to find a way to create a selector for your save buttons. Like this:
$(document).ready(function(){
$('.saveButton').bind("click", function(e) {
$(this).attr("disabled", "true");
return true; //causes the client side script to run.
});
});
In this example, I assumed that all the save buttons would have the css class ".saveButton", but you can find your own way to select the button.
Cheers!
You can also try disabling it via Javascript.
You need to use JavaScript to alter the link once it's clicked to prevent future click handling, before allowing the page to proceed with the postback. A naive attempt would be,
<asp:LinkButton runat="server" id="button" OnClientClick="this.href='#'">
Click - doesn't quite work
</asp>
This successfully prevents successive clicks from triggering the postback, but it also prevents the first click from triggering the postback. A little more logic is required to make this work correctly. In the codebehind, I grab the actual postback JavaScript snippet and work it into some logic.
protected void Page_PreRender(object sender, EventArgs e)
{
button1.OnClientClick = string.Format(
"if(this.getAttribute('disabled')) return false; {0}; this.setAttribute('disabled','disabled'); return false;",
Page.ClientScript.GetPostBackEventReference(button1, null));
}
In the HTML template:
<asp:LinkButton runat="server" id="button" >
Click - does not allow multiple postbacks
</asp>
You can spruce this up with some CSS, and at that point I would advise including jQuery, so your code is more concise (due to its command chaining).
What you have to do is use some JavaScript and disable it when its clicked on the client side.
That click event fires on a postback.
Simplest way of attaching javascript to disable the button after user click would be this (in page onLoad event):
myButton.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btnSave, null) + ";");
But if button is repeated on many pages, you can maybe create nested master page and put save button there, or inherit you page from class that implements this disable functionality. Also, you can "scan" for control you want to disable after click!

Categories

Resources