show string in asp.net C# messagebox - c#

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

Related

SetFocus to Control From Code Behind with JavaScript

I am trying to set focus to a page control (Textbox) by using the registerStartupScript method. However, I have been unsuccessful. Here is what I have tried:
ClientScript.RegisterStartupScript(this.GetType(), "SetFocus", "<script>document.getElementById('" + this.tbAdjust.ClientID + "').focus();</script>");
And:
ClientScript.RegisterStartupScript(GetType(), "focus", "<script>$('" + this.tbAdjust.ClientID + "');</script>");
Can't seem to get it. Seems like a pretty straight forward question, if you all need anymore code, let me know. Thanks in advance for any help!
Normally tbAdjust.Focus(); at code behind should work. Here are the scripts.
Without Ajax
ClientScript.RegisterStartupScript(this.GetType(), "focus",
"document.getElementById('" + this.tbAdjust.ClientID + "').focus();", true);
With Ajax
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "focus",
"document.getElementById('" + this.tbAdjust.ClientID + "').focus();", true);
If you want to use jQuery, you need # at the front.
For example, "$('#" + this.tbAdjust.ClientID + "').focus();"
Wouldn't jQuery's .ready() method work?
$(document).ready(function() {
$('#target').focus();
});
Try Page.RegisterClientScriptBlock instead:
Page.RegisterClientScriptBlock("SetFocus", "<script>document.getElementById('" + this.tbAdjust.ClientID + "').focus();</script>");

Unterminated string constant error in asp.net

Got this error while call the function
static public void DisplayAJAXMessage(Control page, string msg)
{
string myScript = String.Format("alert('{0}');", msg);
ScriptManager.RegisterStartupScript(page, page.GetType(), "MyScript", myScript, true);
}
Calling this function:
string sampledata = "Name :zzzzzzzzzzzzzzzz<br>Phone :00000000000000<br>Country :India";
string sample = sampledata.Replace("<br>", "\n");
MsgBox.DisplayAJAXMessage(this, sample);
I need to display Name,Phone and Country in next line.
Unterminated string constant means you've forgotten to close your string. You can't have an alert that runs over multiple lines. When the script is outputting to the browser, it's actually including the new lines.. not the "\n" like the javascript expects. That means, your alert call is going over multiple lines.. like this:
alert('Name :zzzzzzzzzzzzzzzz
Phone :00000000000000
Country :India');
..which won't work, and will produce the error you're seeing. Try using double backslash to escape the backslash:
string sample = sampledata.Replace("<br>", "\\n");
"\n" is a newline for C#, i.e. your js contains:
something('...blah foo
bar ...');
what you actually want is a newline in js:
something('...blah foo\nbar ...');
which you can do with:
string sample = sampledata.Replace("<br>", "\\n");
or:
string sample = sampledata.Replace("<br>", #"\n");
You need to escape/encode your string being consumed by JavaScript:
Escape Quote in C# for javascript consumption
Your Unterminated is not in C# is in Javascript generated code.

How to make a function into a class or module in c#

I am just learning how to use classes in my projects. I have been working on a DataAccessClass.cs and am doing well (I think).
Taking a break from data access, I decided to try to make a void into a class. This void sends a message to the client as a javascript alert. It works well, but has to be included on each page. When I tried to make it a class, I was informed that my class does not contain a definition for ClientScript. I included all the "using" directives from the original page to no avail... Any hints or suggestions would be greatly appreciated.
The original code:
//------------------------------------------------------------------------------
//Name: SendErrorMessageToClient
//Abstract: show alert on client side
//------------------------------------------------------------------------------
protected void SendErrorMessageToClient(string strErrorType, string strErrorMessage)
{
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = "<script type=\"text/javascript\" language=\"javascript\">alert( '" + strErrorType + "\\n\\n" + strErrorMessage + "' );</script>";
this.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}
Messages are sent into this void like this:
if (DataAccessClass.OpenSqlConnection(ref Conn, strConn, out strErrorMessage) == false)
{
string strErrorType = "Database Connection Error:";
SendErrorMessageToClient(strErrorType, strErrorMessage);
}
Or this:
catch (Exception excError)
{
string strErrorType = "Unhandled Exception:";
string strErrorMessage = excError.Message;
SendErrorMessageToClient(strErrorType, strErrorMessage);
}
You are receiving the error as 'Clientscript' is a property derived from a System.Web.UI.Page and by moving into a separate class file, you no longer have access to this property.
You could solve this by passing in the page as well, and amending the code to
protected void SendErrorMessageToClient(string strErrorType, string strErrorMessage, Page page)
{
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = "<script type=\"text/javascript\" language=\"javascript\">alert( '" + strErrorType + "\\n\\n" + strErrorMessage + "' );</script>";
page.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}
ClientScript Property is part of the Page class that every ASPX page inherit from. Therefore you can not just use it from inside your class unless it (i.e. your class) has Page as its base class.
this. is for fields in your method in classes.
Why do you want to make this a class? It shouldn't be a class, it doesn't have any properties or fields, unless you can think of one. You do understand if you make it a class you would still have to intialize it on every page.
You could make it a static string method you would still have to include this on every page.
this.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
You'll need to pass the page into the function
SendErrorMessageToClient(Page page, string strErrorType, string strErrorMessage)
so that you can change
this.ClientScript...
to
page.ClientScript...
The reason being that ClientScript is part of the Page class
Or, possibly better, pass the ClientScript object, rather than page.
So your definition would look like
SendErrorMessageToClient(ClientScript clientScript, string strErrorType, string strErrorMessage) {
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = String.Format("<script type='text/javascript' language='javascript'>alert('{0}\\n\\n{1}');</script>",
strErrorType, strErrorMessage);
clientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}

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