How can WebForm_OnSubmit be undefined? - c#

In my current project I've got a workflow in which I need to show two consecutive MessageBoxes to the user. The first one is more like a warning, that informs the user of the risk of the operation he tries do execute. I am using the ClientClickEvent of a link button to let the user confirm the operation:
<asp:LinkButton runat="server" id="lockorder"
CommandName='LockOrder'
OnClientClick="return confirm('Do you really want to lock this order?');" />
If the user confirms that he is sure to perform the operation, the application performs some validation from code behind. The result can be, that there are some unhandled tasks. This is valid, but the user should get informed about it, to have the possibility to finish those tasks. So I show a second confirmation dialog, but this time from code behind:
if (tasksOpen)
{
ScriptManager.RegisterClientScriptBlock(
this.Page,
typeof(Page),
"Onload",
"var confirmationResult = window.confirm('There are some open tasks left, which might get closed. Do you really want to lock this order?'); if (confirmationResult) __doPostBack('ConfirmLockOrder', confirmationResult);",
true);
return;
}
For better readability here is the JS-snippet that get's handed to the client:
var confirmationResult
= window.confirm('There are some open tasks left, which might get closed. Do you really want to lock this order?');
if (confirmationResult)
__doPostBack('ConfirmLockOrder', confirmationResult);
Back again in code behind I am receiving this command (e.g. inside the Page_Load event) and continue with the actual operations. All worked fine, but with some change I've done it stopped performing the postback.
I've took a look at the client script using FireBug. The __doPostBack-function (which is apparently auto-generated) tells me that WebForm_OnSubmit is not defined. I think it is not defined, because the confirmation dialog get's shown in the OnLoad-event and thus before the form is actually loaded. But why does the __doPostBack-function even need to check if this event performed, if it is not defined? Can I customize the __doPostBack-behaviour? Or should I choose another event? Or am I completely wrong here?
I hope somebody can point me into the right direction!

Based on the error (and some educated guesses), your JavaScript code that you are registering via ScriptManager is firing before the rest of the JavaScript code generated by ASP.NET is loaded. Hence, WebForm_OnLoad is undefined.
You need to make certain that the web page is completely loaded before your code executes. Change your code to the following:
window.onload=function(){
var confirmationResult = window.confirm('There are some open tasks left, '
+ 'which might get closed. Do you really want to lock this order?');
if (confirmationResult)
__doPostBack('ConfirmLockOrder', confirmationResult);
}
*I broke the confirm string into two, just for display purposes.
If you use jQuery, $(document).ready is preferred over window.onload.

Related

How to stop errors from showing on web pages, show on pop up instead?

i am developing this app which is going to be a template in my organization, but there is a problem i need to solve. I want to show errors on an AjaxControlTookit's modalpop and never let it show that ugly yellow text on the browser with stacktrace.
WHERE should i intercept and WHAT should i intercept for this to work?
Is there an lifecycle event i can use that happens before rendering but after the page is itself contructed (and thus the error has happened?) at that event, will i have the page controls ready? Assuming i have a masterpage and the modalpopup will be there, could i do this general error handling in the masterpage?
Is this something i need to use global.asax? (i have never used it, but with a name like that and the events it has, i can figure what it does)
Is this something doable even? could i catch every exception, even browser errors that happened related to my pages?
Edit:
My problem isn't really with what the user sees, is that i don't want the browser to display the stack trace and the yellow error page, destroying anything the user has done so far.
I want to create a nice and clean user experience and if the user can recover from whatever issue is causing the exception i want them to have the option, which include not destroying the page they had before the post-back. Is that understandable or i am unable to explain this any better?
You could easily do this using javaScript:
window.onerror = function(msg, url, linenumber) {
alert('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);
return true;
}
http://www.javascriptkit.com/javatutors/error2.shtml
Generally speaking, here is a link on how to handle errors (including global errors) in ASP.NET:
How to: Display Safe Error Messages
Then with regards to the modalpopup, in the samples mentioned in the link, the user was redirected to some other error page. You can pass the error messages to that error page and then display the modelpopup on that error page.

How to use javascript confirmation method on code behind [duplicate]

This question already has answers here:
Javascript confirm box in C# code behind
(3 answers)
Closed 9 years ago.
else if (Result == 1)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Test", "return confirm('Are you sure you want to delete? This action cannot be undone.')", true);
FSI.DeleteINsertData(ID.ToString(), No.ToString());
}
I have a js confirmation on code behind. I want to continue process when the user click "yes", otherway , user click "no", do nothing. it is in else if statement.Thanks for your answers.
Use:
Response.Write("<script>confirm('Are you sure you want to delete? This action cannot be undone.');</script>");
Might Work!
Your question implies that what you want to do is pause the server-side code (before you delete anything) while you wait for some client-side code to execute (throwing up the confirmation box to make sure the user does want to perform the delete). This simply isn't the way things work.
All the ScriptManager.RegisterClientScriptBlock(...) call does is tell the server that it should include that script when it sends the response to the client. It doesn't then pause and send the script; instead it just carries on, executing the deletion and then the page and script gets sent to the client. You can't change that behaviour - it's a fundamental part of how server-side web programming works.
Your options really are to have the delete button/link that they clicked in the first place throw up the confirmation box before you even go to the server (cancelling the form-submission or link-click if they've changed their minds), or alternatively to have the server reply to that submission/click with a confirmation page that requires them to click another button, which then goes back to the server again to actually perform the delete.
I think you can make merge between server side and Client side.
You can add your script as code behind:
string scriptStr = "<script>var confirmation = confirm('something');
if(confirmation){document.getelementbyid('button').click();}
else{//something else}</script>";
RegisterStartupScript("ScriptFunction", scriptStr );
and then in your code behind handle the button click event.
This may works for you.

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

confirm message box

I have a save button which when clicked should make some changes in the database.
if (bFound== false)
{
// Giving the warning message
// If user presses cancel then abort
// Prepare the list of dbId needs to be deleted
deletedBSIds.Add(dbId);
}
Here if the bFound field is true it should not execute the above statement, but if it is false it should go in the condition and then ask if the user want to save changes "yes" or "no".
If the user says yes it should go to the command "deletedBSIds.Add(dbId);" and keep executing further but if the user presses No it should basically abort and do nothing at all.
Is there a way to do this?
Any help would be appreciated.
This is a server side event. so i think cannot add a click event in my button/..
Here the message box only pops up if the bFoung field is false. or else it will not pop up at all.
Please correct me if u feel i am wrong..
thanks
You'll want to add the following to the button:
button.OnClientClick = "return ConfirmThis();";
You'll then need to add the ConfirmThis function to the Page:
Page.ClientScript.RegisterScriptBlock(GetType(), "ConfirmThis",
#"function ConfirmThis() {
if(condition) { //where condition checks the bfound element.
return confirm(""Are you sure you want to delete this?"");
}
return true;
}");
Doing this approach you're going to want to try and be able to test the bfound condition on the client side in the javascript. If the bfound value is stored in a textbox or HiddenField you should use the document.getElementById function. If the bfound value is known when you are creating the page, you can inject it into the ConfirmThis function directly, of pass it into the ConfirmThis function as a parameter.
Edit in response to your edit:
You have two options when trying to elicit a confirm from the user:
Using client side logic that is already sent to the browser to perform the confirm. This is the example that I have given above.
The "Other" option is to send the page back with a modal dialog, or using the confirm box. You will then get the user's confirmation back in a completely new postback to the server. So you'll need to rethink your logic to be able to temporarily store the information from the first post back and wait for the second post back to finalize the desired action.
Of the two examples, the first option is cleaner and requires no temporary memory and saves the user an additional postback.
Because both options are going to require you to rework the logic asking for the confirm, if at all possible I would try to convert the logic required for the condition to show the confirm dialog to be able to be performed on the client's computer with javascript.
Is there any way you can precalculate the bfound variable, or at the least, send enough information for it to be calculated on the client?
If you still feel like using option 2 after all of my pleading:
use the following code (based on http://www.dotnetspider.com/resources/1521-How-call-Postback-from-Javascript.aspx:
if(bfound)
{
//save all the information you need in temporary information
ViewState["InformationINeedToFinishAfterPostback"] = ImportantInformation;
Page.ClientScript.RegisterScriptBlock(GetType(), "postbackmethod", Page.ClientScript.GetPostBackEventReference(this, "MyCustomArgument"));
Page.ClientScript.RegisterStartupScript(GetType(), "startupconfirm",
#"if(confirm(""are you sure?"") {
__doPostBack('__Page', 'MyCustomArgument');
}");
}
Now to handle the postback add the following code to your page_load:
if(Request("__EVENTARGUMENT") == "MyCustomArgument")
{
ImportantInformation = (CastToAppropriateType)ViewState["InformationINeedToFinishAfterPostback"];
//finalize the desired action here.
}
But... I would still recommend the first option. But now you have the code you will need for both options. Also, I didn't test this code, so you're bound to encounter syntactic problems, but it gets you on the right track.
I'm not all that sure what bfound is supposed to represent, but you can't execute 1/2 way through some server code and then go back to the client- ASP.NET does not work that way.
Typically you will do the confirmation with some client side JavaScript. Google ASP.NET Yes/no confirm to find lots of different ways to do this...
Once you've done this you can then conditionally execute the server side code.
You could use the Javascript confirm() function to display a dialog box to the user with 'OK' and 'Cancel' prompts. You could then store the user's choice in a hidden field and trigger a postback. This article explains how to render Javascript code to the client using ASP.NET.
Since you are using ASP.NET you can add an attribute to your button:
btnDelete.Attributes.Add("onclick", "return confirm('Are you sure?');");
Where btnDelete is your Button.

Updating ASP.NET label while processing

I have a method thats run on a button click, with 4 labels. What I need to do is update a label after each block of code executes. I've tried threading, updatepanels, etc and can't seem to get anything to work. I thought the timer would work, but it only ticks when you're not inside a method. The code looks something like this:
private void SomeMethod()
{
label1.text = "Processing...";
AnotherMethod();
label1.text = "Done.";
label2.text = "Processing...";
AnotherAnotherMethod();
label2.text = "Done.";
//etc...
}
You have a misunderstanding of how asp.net works. Your server code runs in response to a request from a browser for a complete html page. This is true even when all you really want to do is run some button click code. The entire page must be rebuilt from scratch anyway, even on postbacks. It's just the way web forms are designed.
As soon as the page is rendered to the browser, that instance of your page class is destroyed. On the next postback you'll start from scratch again, with the notable exceptions of the session, viewstate, and the application cache. Even the page's previous DOM instance in the browser is replaced.
So when you set the text property of the label you aren't directly updating anything visually in the browser. All you are doing is updating some temporary storage in your page class. As the last stage of executing your server code, all those temporary variables are used to render the completed html and the response is finally sent to the browser and shown to the user.
That should be enough information to give you an understanding of why your code doesn't behave as expected. It's running all of the code in the method before any of your property changes make their way to the browser. Therefore, the only thing the user sees is the final state of the operation.
Now ajax can complicate things a bit. When using an ajax control you might not be updating the entire page anymore, but the concept still applies: one request is made, and one response is received and used to update the entire context of the request. You can further muddle things if you have a lot of javascript in place to handle the result of the ajax request.
Unfortunately, there's no quick fix for the code you posted. You'll need to think about how this really works and decide how you want your page to flow.
Can you expose the 3 methods to client script and then call them sequentially from your client side code, when method1 finishes the client script would update the ui then call method2, and so on...

Categories

Resources