Issues with displaying messagebox in asp.net - c#

I have the following message box in c# on my asp.net page inside the btnSubmit_Click event.
It tends to popup sometimes and not popup sometimes. Any reasons as to why it is not consistent?
ClientScript.RegisterStartupScript(
GetType(),
"alert",
"alert('An email has been sent to Customer Service');",
true);

I guess that this will depend on the text you are putting inside the alert. In the example you provided the text is hardcoded but I suppose that in your real application this text is dynamic and might contain characters that break javascript such as '. Try using FireBug to see if there are some javascript errors when it doesn't work.

Have You checked, if the alert('An email has been sent to Customer Service'); line is in the HTML Source after you clicked the Button and the message did NOT appear?
If it isn't in the HTML, check:
with the Debugger if your
codeblock is hit
are you maybe redirecting the response?

try these popups instead
type java directly in the visualstudio GUI
On a button go to the "OnClientClick" property (its not into events*) over there type:
return confirm('are you sure?')
it will put a dialog with cancel ok buttons transparent over current page if cancel is pressed no postback will ocure. However if you want only ok button type:
alert ('i told you so')
The events like onclick work server side they execute your code, while OnClientClick runs in the browser side. the come most close to a basic dialog
as this codes is so small it should work unless they have really strange browser clients

Related

Confirming asp c# action on page load

I've been searching for an answer to this but haven't found what I'm looking for yet.
When I load into the page there is a check run one the server side. Depending on the output of this (bool), I wish to display a "yes no" confirm box to execute another piece of server side code.
I have found ways to do this easily enough on a button click but I'm trying to avoid adding a hidden button and simulating a click.
MessageBox.Show isn't an option in this case as I get the following error:
Showing a modal dialog box or form when the application is not running
in UserInteractive mode is not a valid operation
Is there any way to achieve this without simulating a button click?
Cheers,
Spitfire2k6
In web app (including the one created with ASP.NET) you can use Javascript confirmation dialog box: window.confirm("Request to Confirm Text");, and process User's response like in the following sample code snippet:
var _response = confirm("Please Confirm");
if (_response == true) {//Do Action1}
else {//Do Action1}
Pertinent to your case, you can use for e.g. page <body onload> event. Hope this may help.
I realised I was going about this all wrong.
The check is now done on page load, depending on the result I'm showing an asp panel with 2 asp buttons as a confirm box.
Thanks for all guidance.
Cheers,
Spitfire2k6

Calling a confirm dialog box on code behind and get the chosen option

I'm developing an asp.net application and I need to call a confirm dialog box on the code behind. And after that, I need to get the user's click (if he clicked at OK or Cancel).
If he clicked the OK button of the dialog, I must continue to running the code where I stopped before call the dialog.
To solve this problem I thought in put at the aspx an input of type button, and set it's style to visibility:hide. So, when the users click on the OK button the programm will call this hidden button which calls a method that will continue the job stopped.
I'll post my code, I expect it might help.
The code below is on my code behind, and it calls the confirm dialog.
System.Web.UI.
ScriptManager.RegisterClientScriptBlock(this, GetType(), "__Mensagem", "if (confirm('" + CustomMessage + "')){document.getElementById(\'<%=btnSave.ClientID%>\').click();}", true);
The code below is on my aspx, it's the "hidden" button.
<input style="visibility:hidden;" id="btnSave" runat="server" onclick="btnSave_Click"/>
I don't know why isn't working. The error that I receive after click on the button OK of the confirm dialog box is the following: Erro em tempo de execução do Microsoft JScript: 'document.getElementByID(...)' é nulo ou não é um objeto
I'm from Brazil so the error is in portuguese, a translation to english it's something like this:
"A runtime error occurred on Microsoft JScript 'document.getElementByID(...)' is null or is not an object"
I give a look at the html code of the page and I notice that the button isn't there.
Maybe it's because I'm using an UpdatePanel, but when I removed it (just for tests, I must use the Update Panel), the same error is showed, and in this time the button were on the page's html code.
A stab in the dark.
In your code-behind have you set btnSave.visible = false;? If so, this would prevent the button from being rendered to the HTML.
Also, is there any reason you're not using the ASP:Button control, rather than a mix of HTML with runat="server"?
Finally, it may help to have type='button' on your <input....
UPDATE
The problem is you're trying to apply an inline tag
document.getElementById(\'<%=btnSave.ClientID%>\')
in your code be <%=btnSave.ClientID%> does not exist yet.
your code will break the moment you put your button inside another server control, as the clientId will become different.
Change the code to this:
document.getElementById('" + btnSave.ClientID + "')
and it will work, regardless of where you have the button.
Once your page is rendered in browser, right click on it, and say "view Source". check the HTML and try to find your hidden button, if you find it, use its id in your statement getElementById(\'<%=btnSave.ClientID%>\') . If you dont find your button, then probably you have set its visibility to false from your code-behind somewhere, remove that, follow the above process again and you should be ok.
I solved the problem replacing the part
document.getElementById(\'<%=btnSave.ClientID%>\').click();
by
$(\"#ctl00_body_btnSave\").click();
I also replace the input element by an asp:Button.
Give a look how my code is on my code behind now:
System.Web.UI.
ScriptManager.RegisterClientScriptBlock(this, GetType(), "__Mensagem", "if (confirm('" + CustomMessage+ "')){$(\"#" + btnSave.ClientID + "\").click();}", true);
And on my aspx:
<asp:Button id="btnSave" Width="0px" Text="" runat="server" onclick="btnSave_Click"/>
The use of Widht="0px" and Text="" to hidden the button isn't recommended, but I used because it won't cause me problems. It's recommended the use of a CssClass which make it hide.
So, if the user confirm the operation, the even btnSave_Click is called.
Thanks for all the answers.

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

Refreshing the asp.net web page after validation

I have an asp.net web page (C# 2008) where the user would enter an EmployeeID, and when they tab out of the textbox (the page executes a validation code block in the codebehind), they get a messagebox prompting them to select one of two values from a dropdown listbox.
The code for the message prompt in the codebehind is :
Response.Write("<script>window.alert('Please select Alpha or Beta')</script>");
After the prompt is displayed, and the user clicks "ok" and returns to the page, the text on the page appears distorted (the text in labels are a size larger, the labels get wrapped to another line etc)
I tried putting a Response.Redirect("UserProfileMaint.aspx"); after the messagebox in the codebehind, but now, the messagebox does not appear;
So this is my squence:
User enters EmployeeID
If user has NOT selected Alpha or
Beta, then show messagebox
If user HAS selected Alpha or Beta,
then don't show messagebox
I want to display the messagebox validation, and ensure the appearance of the text on the page is not distorted. How can I do this?
Response.Write writes directly to the output stream, placing it before <html> which the browser gets very confused by (causing your text issues). What you want to do instead is this:
ClientScript.RegisterStartupScript(GetType(), "alert",
"alert('Please select Alpha or Beta');", true);
ClientScript.RegisterStartupScript includes the script in the page to be run on load rather than put in the response too early. The last argument: true is telling it to wrap that alert in <script> tags, keeping your code-behind cleaner.
The best way to handle this would be to use Javascript and do Client side validation. If you really want to do server side validation then instead of showing a alert by using Response.Write you should use RegisterStartupScript or better show the message using a Label at the top.
HTH
When you call Response.Redirect, that occurs on the server side, whereas you want the redirect to occur on the client side after a choice is made.
To do that, when you write your script with Response.Write (btw, there are much better ways to do this), you would have logic that determined what the user selected, and then based on the selection, either requery them for data, or set the location property of the inherent document object to the url you want to redirect to.

ClientScript.RegisterClientScriptBlock?

In my web application when i upload a video and click the save button, if the video is uploaded i write the code to display the message video is uploaded. My code is as follows:
ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('Inserted successfully');</script>", false);
When the alert box appears is comes with a white background. I clicked on ok button in that alert box but the page is not going back to the previous page it is showing the same white space.
Can you solve the problem.? If you not understand i will explain clearly.
In local it is working fine but when i update in online it is not working.
Hai sridhar,
I found an answer for your prob
ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('Inserted successfully');</script>", true);
change false to true
or try this
ScriptManager.RegisterClientScriptBlock(ursavebuttonID, typeof(LinkButton or button), "sas", "<script> alert('Inserted successfully');</script>", true);
The method System.Web.UI.Page.RegisterClientScriptBlock has been deprecated for some time (along with the other Page.Register* methods), ever since .NET 2.0 as shown by MSDN.
Instead use the .NET 2.0 Page.ClientScript.Register* methods.
- (The ClientScript property expresses an instance of the ClientScriptManager class )
Guessing the problem
If you are saying your JavaScript alert box occurs before the page's content is visibly rendered, and therefore the page remains white (or still unrendered) when the alert box is dismissed by the user, then try using the Page.ClientScript.RegisterStartupScript(..) method instead because it runs the given client-side code when the page finishes loading - and its arguments are similar to what you're using already.
Also check for general JavaScript errors in the page - this is often seen by an error icon in the browser's status bar. Sometimes a JavaScript error will hold up or disturb unrelated elements on the page.
See if the below helps you:
I was using the following earlier:
ClientScript.RegisterClientScriptBlock(Page.GetType(), "AlertMsg", "<script language='javascript'>alert('The Web Policy need to be accepted to submit the new assessor information.');</script>");
After implementing AJAX in this page, it stopped working. After reading your blog, I changed the above to:
ScriptManager.RegisterClientScriptBlock(imgBtnSubmit, this.GetType(), "AlertMsg", "<script language='javascript'>alert('The Web Policy need to be accepted to submit the new assessor information.');</script>", false);
This is working perfectly fine.
(It’s .NET 2.0 Framework, I am using)

Categories

Resources