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
Related
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("};");
to print my Gridview i used following event Button_Print_Click. below is my code:
private void Button_Print_Click(object sender, EventArgs e)
{
GridView1.PagerSettings.Visible = false;
GridView1.DataSource = DataLoad();
GridView1.DataBind();
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
string gridHTML = sw.ToString().Replace("\"", "'").Replace(System.Environment.NewLine, "");
StringBuilder sb = new StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload = new function(){");
sb.Append("var printWin = window.open('', '', 'left=0");
sb.Append(",top=0,width=1000,height=600,status=0');");
sb.Append("printWin.document.write(\"");
sb.Append(gridHTML);
sb.Append("\");");
sb.Append("printWin.document.close();");
sb.Append("printWin.focus();");
sb.Append("printWin.print();");
sb.Append("printWin.close();};");
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "GridPrint", sb.ToString());
GridView1.DataSource = DataLoad();
GridView1.DataBind();
}
But by focusing the page, it doesn't show the css properties. For example my GridViewHeader text font looks simple but not bold!! is there anything wrong with the code? Why dont I get the original CSS styled page printed?
Please help thank you.
The problem is that you are calling a pop-up using window.open(), this popup opens a new HTML page, and even if you inject javascript generated HMTL in it, it doesn't have any reference to your CSS file.
Try to add a link to it in the string output
sb.Append("printWin.document.write(\"");
sb.Append("<link rel='stylesheet' type='text/css' href='...your.css'>")
sb.Append(gridHTML);
Note that this is really an odd way to print a html page, I would find it more simple to generate a extra Print CSS for this using the #media rules, and call the javascript print() on the very same page : see eg http://edutechwiki.unige.ch/en/CSS_for_print_tutorial
<%--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 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.
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?