I am trying to call a javascript simple alert function when I catch an exception in my C# code as follows:
inside my function:
try
{
//something!
}
catch (Exception exc)
{
ClientScript.RegisterStartupScript(typeof(Page), "SymbolError",
"<script type='text/javascript'>alert('Error !!!');return false;</script>");
}
Is there another way I can do this, because this doesn't show any alert boxes or anything??
It's because you'll get the error along the lines of:
Return statement is outside the
function
Just do the following, without the return statement:
ClientScript.RegisterStartupScript(typeof(Page), "SymbolError",
"<script type='text/javascript'>alert('Error !!!');</script>");
The above should work unless if it is inside update panel. For ajax postback, you will have to use ScriptManager.RegisterStartupScript(Page, typeof(Page), "SymbolError", "alert('error!!!')", true); instead.
Its the return, the below code works:
try
{
throw new Exception("lol");
}
catch (Exception)
{
ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'>alert('Error!!!');</script>", false);
}
Try this
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "SymbolError", "alert('error');", true);
Try to use the following:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "AnUniqueKey", "alert('ERROR');", true);
I use this code in an asp.net project
public void MsgBox1(string msg, Page refP)
{
Label lbl = new Label();
string lb = "window.alert('" + msg + "')";
ScriptManager.RegisterClientScriptBlock(refP, this.GetType(), "UniqueKey", lb, true);
refP.Controls.Add(lbl);
}
And when I call it, mostly for debugging
MsgBox1("alert(" + this.dropdownlist.SelectedValue.ToString() +")", this);
I got this from somewhere in the web, but was like a year ago and forgot the real original source
here are some related links:
Diffrent Methods to show msg box in Asp.net on server side - Coding Resolved
Create a Message Box in ASP.NET using C# - Blog Sathish Sirikonda
Related
Hi I want to call a client side javascript confirm message from code behind in asp.net.
I want to use the true or false return value from the confirm message.
I'm doing like this, but this is not the correct way, please tell me how can I do the same.
ScriptManager.RegisterStartupScript(this, this.GetType(), "myconfirm", "confirm('No Rule Type Ids found for This Rule.');", true);
I think This is what you want to achieve:
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to save data?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
.aspx code
<asp:Button ID="btnConfirm" runat="server" OnClick = "OnConfirm" Text = "Raise Confirm" OnClientClick = "Confirm()"/>
C#
public void OnConfirm(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked YES!')", true);
}
else
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked NO!')", true);
}
}
Instead of directly writing confirm in the code behind. Write the name of javascript function.
Forexample,
ScriptManager.RegisterStartupScript(this, this.GetType(), "myconfirm", "OpenConfirmDialog();", true);
In your javascript, write the function OpenConfirmDialog
<script>
function OpenConfirmDialog()
{
if (confirm('No Rule Type Ids found for This Rule.'))
{
//True .. do something
}
else
{
//False .. do something
}
}
</script>
You can't mix client-side code with server-side code. The client side code (javascript) will not be sent to the client (browser) until the server-side code has completed.
You will need to stop processing and show the question to the user (maybe by a redirect to some other page), and then (on confirm) continue with your processing.
Response.Write("<script language=javascript>");
Response.Write("if(confirm('El vehiculo no existe, Deseas crear el registro?')){window.location.href='IngresoVehiculos.aspx'}");
Response.Write("</script>");
use:
Response.Write("<script>alert('Open Message!');</script>");
You can do it without using Javascript function
Try
if (MessageBox.Show("confirm('No Rule Type Ids found for This Rule.')",
"myconfirm",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// yes
}
else
{
//No
}
I want to show a sting in a asp.net messagebox with C#.
This time I´m using the RegisterClientScriptBlock
this.RegisterClientScriptBlock("scriptfails", "<script language='javascript'>alert('This is a test, just klick OK'); </script>");
Is it possible to show a string in there or do I have to use another messagebox method?
Thanks in advance.
You can generalize the method in this way:
public void ShowMyMessage(string myMessage) {
this.RegisterClientScriptBlock("scriptfails", "<script language='javascript'>alert('" + myMessage + "'); </script>");
}
and call from somewhere:
ShowMyMessage("Hi!!");
It's just an example it could be better, but can give you the idea.
Try this:
var message = "this is my string";
this.RegisterClientScriptBlock("scriptfails", string.Format("<script language='javascript'>alert('{0}'); </script>", message));
use
this.RegisterClientScriptBlock("scriptfails", string.Format("<script language='javascript'>alert('{0}'); </script>", "yourmessage"));
<%--Confirmation Box--%>
<script type="text/javascript" language="javascript">
function alertbox() {
if (confirm("Are you sure?") == true)
{
document.getElementById('<%= hdnYesNo.ClientID %>').value = "YES";
}
else
{
document.getElementById('<%= hdnYesNo.ClientID %>').value = "NO";
}
}
</script>
How to rewrite this code in C# as codebehind? I would like have a confirm box with yes or no buttons.
protected void Page_Load(object sender, System.EventArgs e)
{
string csName = "PopupScript";
Type csType = this.GetType();
ClientScriptManager csm = Page.ClientScript;
if (!csm.IsStartupScriptRegistered(csType, csName)) {
StringBuilder sb = new StringBuilder();
sb.Append("<script>");
sb.Append("function alertbox() {");
sb.Append("if (confirm('Are you sure?') == true) ");
sb.Append("{");
sb.Append("document.getElementById('" + hdnYesNo.ClientID + "').value = 'YES';");
sb.Append("}");
sb.Append("else");
sb.Append("{");
sb.Append("document.getElementById('" + hdnYesNo.ClientID + "').value = 'NO';");
sb.Append("}");
sb.Append("</script>");
csm.RegisterStartupScript(csType, csName, sb.ToString());
}
}
you can use like this way
Page.ClientScript.RegisterStartupScript(this.GetType(), "Confi", "if(confirm('Are you sure?') == true){ document.getElementById('txtValue').value ='YES';}else{document.getElementById('txtValue').value ='NO';}", true);
You can use ClientScriptManager class and its methods, for example RegisterClientScriptBlock. Depends on when you want the javascript to execute.
See details here:
http://msdn.microsoft.com/en-us/library/System.Web.UI.ClientScriptManager_methods.aspx
You need javascript for this, it's not possible in code behind. Code behind is run on the server before the page is sent to the user, javascript is run on the user's computer.
If you want to get access to their answer in code behind (possible and straightforward), you can use ajax or you can postback.
If you want to have this popup to come up when you press on a .Net asp:button control, then you can put a javascript function in the "OnClientClick" attribute of the control.
EDIT: If you need help with any of the above, let us know and help will be provided :).
EDIT2: Due to the discussion below, I guess I should clarify: You can (obviously) construct javascript on the server side before passing it to the client, but the example you gave is NOT a case where you should be doing that (an example of where this might be a good idea would be a script that has variables read from a database or something similar that doesn't need to be dynamic between page loads).
another option is to create the script in the /View folder and user razor for generating the script.
then you could point to the page in the tag like
<script src="~/ScriptGenerator/MyScript" />
for pointing the controller ScriptGeneratorController that expose the action MyScript
I've got almost got a web project finished for an assignment, but I've hit a stumbling block in the form of an alertbox that refuses to pop up when called. The assignment is to create a web form for users to submit personal information to a website. Once they fill in all the textboxes and click a button to register, that will call the function registerMe in the code behind as seen below. Once they do that, the idea is that the function will first check to make sure that the user hasn't already registered on the website, then it will stuff all the values from the Textboxes into a Session object (which is using Candidate.curCandidate as a wrapper). This Session object will then be added to the Application state data to save it.
Now, here's the weird thing. In the if statement below, if the statement is true, all the values will be saved to the session and then the Application state data as desired, but the Alertbox won't appear. However, if the if statement is false, an Alertbox WILL appear. So, I'm guessing that somehow reading and writing all these values is interfering with the activation of an Alertbox, but I have no idea why.
protected void registerMe(object sender, EventArgs e)
{
String successText;
if (Candidate.curCandidate.appProperty == false)
{
Candidate.curCandidate.ssNumberProperty = socSec.Text;
Candidate.curCandidate.emailAddressProperty = email.Text;
Candidate.curCandidate.userIDProperty = userName0.Text;
Candidate.curCandidate.passwordProperty = password0.Text;
Candidate.curCandidate.dateOfBirthProperty = dateBirth.Text;
Candidate.curCandidate.firstNameProperty = fName0.Text;
Candidate.curCandidate.lastNameProperty = lName0.Text;
Candidate.curCandidate.streetAddressProperty = strAdd0.Text;
Candidate.curCandidate.cityProperty = city0.Text;
Candidate.curCandidate.stateProperty = state0.Text;
Candidate.curCandidate.positionProperty = jobs0.SelectedIndex;
Candidate.curCandidate.applicationStatusProperty = appStatus0.Text;
Candidate.curCandidate.appProperty = true;
Application[Candidate.curCandidate.ssNumberProperty]=Candidate.curCandidate;
successText = "Thank you. Candidate Information Added Successfully.\n" +
"E-Mail Address You Entered will be used to notify you of any\n" +
"updates for the position you applied for.";
ClientScript.RegisterStartupScript(this.GetType(), "myalert",
"alert('" + successText + "');", true);
}
else
{
successText = "Registration unsuccessful.";
ClientScript.RegisterStartupScript(this.GetType(), "myalert",
"alert('" + successText + "');", true);
}
}
Try to remove \n from successText and see if it works.
If you really need it, try to double escape it like below:
successText = "... Successfully.\\n"
I have a button and onclick is set to this method which should display a simple JS alert pop up window:
string message = "File is already open. <br>Please close the file and try again.";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
I have used the code above before and it has worked but not this time.
The only difference is that I was using master pages for the other site and not for this one, and this one also has a timer going.
Is there anything JS related to load in the <head> of the aspx page?
protected void btnToCSV_Click(object sender, EventArgs e)
{
try
{
StreamWriter writer = new StreamWriter(#"\\server location\test.csv");
Some writer.write stuff...
writer.Close();
}
catch (Exception ex)
{
lblMessage.Visible = true;
string message = "File is already open. Please close the file and try again.";
ClientScript.RegisterClientScriptBlock(
this.GetType(),
"alert",
string.Format("alert('{0}');", message),
true);
}
}
Try with this simplyfied version
string message = "File is already open. <br>Please close the file and try again.";
ScriptManager.RegisterClientScriptBlock(
UpdatePanel1, // replace UpdatePanel1 by your UpdatePanel id
UpdatePanel1.GetType(), // replace UpdatePanel1 by your UpdatePanel id
"alert",
string.Format("alert('{0}');",message),
true );
You are not encoding anything here:
sb.Append(message);
If the message is Hello Jean d'Arc (notice the single quote) you will end up with the following code:
alert('Hello Jean d'Arc');
I am leaving you imagine the result of this => a javascript error of course.
To fix this error make sure that you have properly encoded the argument. One way to do this is to JSON serialize it:
var serializer = new JavaScriptSerializer();
sb.AppendFormat("alert({0});", serializer.Serialize(message));
Also since you have already includeed the <script> tags, make sure that you pass false as last argument of the RegisterClientScriptBlock function to avoid adding them twice:
ClientScript.RegisterClientScriptBlock(
this.GetType(),
"alert",
sb.ToString(),
false // <!---- HERE
);
And here's how the full code might look like:
var message = "File is already open. <br>Please close the file and try again.";
var sb = new StringBuilder();
sb.Append("<script type=\"text/javascript\">");
sb.Append("window.onload=function() {");
var serializer = new JavaScriptSerializer();
sb.AppendFormat("alert({0});", serializer.Serialize(message));
sb.Append("};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(
this.GetType(),
"alert",
sb.ToString(),
false
);
Another remark is that if you are doing this in an AJAX call you should use the ClientScript.RegisterStartupScript method.