asp.net javascript message not showing up - c#

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.

Related

How to show the "Submit Success" message first then transfer to another page

I am trying to show the "Insert Successful" message in the pop up window first then the page will redirect to the different page. But when I add the Response.Redirect after the java-script, it will jump to next page without showing the message box. Thanks for your help!
try
{
connnew.Open();
cmdnew.ExecuteNonQuery();
string message = "Form Generated Successfully";
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(form1.GetType(), "alert", sb.ToString());
Response.Redirect("AllRecords.aspx");
}
Instead of doing..
Response.Redirect("AllRecords.aspx");
you can try this..
Response.AddHeader("REFRESH","5;URL=AllRecords.aspx");
this will delay the redirect for 5 seconds.
sb.Append("alert('");
sb.Append(message);
sb.Append("')");
sb.Append("location.replace('AllRecords.aspx');");
sb.Append("};");

How to call confirm message from code behind in asp.net?

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
}

The name 'ClientScript' does not exist in the current context

I have a behindcode javascript. it is to show a javascript dialog box.
however, it keep show this error
The name 'ClientScript' does not exist in the current context
This code was put inside masterpage. I had also use the exactly same code at other aspx file, and it work out fine apart from this..
here is my code:
protected void Button2_Click(object sender, EventArgs e)
{
string message = "Order Placed Successfully.";
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()); string script = "alert('abc');";
}
Try:
Page.ClientScript
instead to see if it makes a difference.
For cs file the sample is;
ClientScript.RegisterClientScriptBlock(this.GetType(), "{some text for type}", "alert('{Text come to here}'); ", true);
for masterpage cs the sample is;
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "{some text for type}", "alert('{Text come to here}'); ", true);
On the master page try ScriptManager.RegisterStartupScript() instead. Watch out, the signature slightly differs from Page.ClientScript.RegisterClientScriptBlock().
Documentation of the ScriptManager Class

ScriptManager.RegisterClientScriptBlock problem in updatepanel

Error: missing } in XML expression
source code: http://localhost:3811/Clinic/ScheduleModule/ManageWorkingTime.aspx?ScheduleId=FRXTn%2fX1N8Wy8C%2fdJqQmDjrOEECv%2fRwauMVX6ZTipAM%3d
line: 0, column: 188
code:
<script language='javascript'>$(document).ready(function() {Sexy.alert( "Can not copy files." );});</script>
CODE:
public static void ShowAsync(string sMessage, MessageBoxTypes sType, Control control, Page pPage)
{
StringBuilder sb = new StringBuilder();
sb.Append("<script language='javascript'>");
string sMsg = sMessage;
sMsg = sMsg.Replace("\n", "\\n");
sMsg = sMsg.Replace("\"", "'");
sb.Append(#"$(document).ready(function() {");
sb.Append(#"Sexy." + sType + #"( """ + sMsg + #""" );");
sb.Append(#"});");
sb.Append(#"</" + "script>");
ScriptManager.RegisterClientScriptBlock(pPage, typeof(Page), control.ClientID, sb.ToString(), true);
}
if i change true to false in RegisterClientScriptBlock then i get
error: $ is not defined
source code: http://localhost:3811/Clinic/ScheduleModule/ManageWorkingTime.aspx?ScheduleId=dH0ry1kng6MwGCRgCxXg8N5nCncbzPzn3TAOEI0tAY4%3d
line: 0
i call this popup like:
MessageBox.ShowAsync("Can not copy files.", MessageBoxTypes.alert, this, Page);
What can be wrong. If i copy this (JQUERY)
<script language='javascript'>$(document).ready(function() {Sexy.alert( "Can not copy files." );});</script>
into some .aspx page popup works. But if i call it from code behind and daypilot pro in this updatepanel form then i get this error.
Can be problem that two ajax framewroks mixed themself? How to prevent this?
i try with jquery.noConflict but it is the same
$.noConflict();
jQuery(document).ready(function() { Sexy.alert("Can not copy files."); });
Thx
If you change the last parameter in RegisterClientScriptBlock from true to false it will not add the script tag anymore. Currently with the setting to true, you have the script tag twice. Not sure what happens, but can't be good :-)
$ sounds like jquery? You don't mention what you are using? I mix ASP.NET Ajax with jquery and that works fine. What Version are you on?

Call Javascript function from code-behind in C#.NET

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

Categories