Unable to call jQuery function from class file in C# project - c#

I am working on C# project. On masterpage,I have a jquery function named "myfunction" .
While trying to call this function from a class file I am getting error on browser console "Uncaught ReferenceError: myfunctionis not defined".
function myfunction(){
// code
}
string script = "";
script = "<SCRIPT language='javascript'>myfunction(); </SCRIPT>";
var obj = ((Object)(HttpContext.Current.Handler));
Type scriptType = obj.GetType();
ClientScriptManager cs = ((Page)(HttpContext.Current.Handler)).ClientScript;
cs.RegisterStartupScript(scriptType, "alert", script.ToString());
While working on any C# website, I can call this function from class file as well but here getting error. Even if I use update panel then function executes but without update panel its not executing.

Change the type on the script declaration:
script = "<SCRIPT language='text/javascript'>myfunction(); </SCRIPT>";
Remove the redundant ToString() call:
cs.RegisterStartupScript(scriptType, "alert", script);
And make sure myfunction() is output on the HTML before your script is inserted.

Related

ASP.net alert box using RegisterStartupScript, produce javascript code but with error

I have this C# code in my class:
private static void error_message(Sybase.Data.AseClient.AseException salah)
{
Page executingPage = HttpContext.Current.Handler as Page;
Type cstype = HttpContext.Current.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = executingPage.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, "PopupScript"))
{
String cstext = "alert('" + salah.Message + "');";
cs.RegisterStartupScript(cstype, "PopupScript", cstext, true);
}
}
which produce this code
<script type="text/javascript">
//<![CDATA[
alert('ua_services not found. Specify owner.objectname or use sp_help to check whether the object exists (sp_help may produce lots of output).
');//]]>
</script>
But the alert box doesn't show up, and Chrome logs an error "Uncaught SyntaxError: Unexpected token ILLEGAL "
What's wrong with my code?
Your salah.Message contains a CRLF. Trim it or escape it.
Or wrap RegisterStartupScript in a method that does it.

Why can't i run a javascript function from c# code?

This is a part of the C# code where i want to insert the network graph:
DetailsBody3.Text = "<tr class=\"space\">";
DetailsBody3.Text += "<td>" + "<div id=\"center-container\"><div id=\"infovis\"></div> />";
DetailsBody3.Text += "</div></td>";
DetailsBody3.Text += "</tr>";
In the "infovis" div in the graph code, the graph exists.
And in the graph javascript file:
function init1(){
// init data
}
var fd = new $jit.ForceDirected({
//id of the visualization container
injectInto: 'infovis',
// some other code,
}
I want to call the int1() function and draw the graph in the table created in C# above.
Javascript code runs in the browser. Your ASP.Net C# code runs in the server.
What you actually want to do is add this to the section of your your .aspx file:
<script type="text/javascript">
$(document).ready(
function(){
init();
}
);
</script>
This will call your javascript init() method once the page has loaded.
Try...
Page thisPage = HttpContext.Current.Handler as Page;
if (!thisPage.ClientScript.IsStartupScriptRegistered("run_init1")) {
thisPage.ClientScript.RegisterStartupScript(
thisPage.GetType(),
"run_init1",
"init1();",
true);
}
The above may need to be adjusted a bit depending on what version of the .Net Framework you are using (this works with version 4.0).

Calling jQuery function from C#

I have the function below which needs to be called from C#
$('.image-cropper').each(linkUp);
Can anyone explain how it could be done. I tried using the below code
String csname1 = "PopupScript";
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
StringBuilder cstext2 = new StringBuilder();
cstext2.Append("<script type=\"text/javascript\"> $('.image-cropper').each(linkUp); </");
cstext2.Append("script>");
cs.RegisterClientScriptBlock(cstype, csname1, cstext2.ToString(), false);
but it did not work.
You should really be calling your code inside the jQuery ready function ie:
$(function() {
$('.image-cropper').each(linkUp);
});
The likely reason your code wasn't working was that the image-cropper elements weren't in the DOM when your code was run.

calling javascript from c#

I need to use the javascript functions to show and hide an element on my page, but calling it from within a C# method. Is this possible?
EDIT : I tried RegisterStartupScript (see below) but this did not hide the elements as I had hoped :
HidePopup("CompanyHQSetup", "$('#<%=DivDataProvider.ClientID %>').hide();$('#<%=modalOverlay.ClientID %>').hide();");
private void HidePopup(string Key, string jscript)
{
string str = "";
str += "<script language='javascript'>";
str += jscript;
str += "</script>";
RegisterStartupScript(Key, jscript);
}
EDIT : Got around this by using a hidden field boolean to determine whether or not to hide or show the elements
Yes, check out RegisterClientScriptBlock.
Here's a snippet taken from that link:
public void Page_Load(Object sender, EventArgs e)
{
// Define the name and type of the client script on the page.
String csName = "ButtonClickScript";
Type csType = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
StringBuilder csText = new StringBuilder();
csText.Append("<script type=\"text/javascript\"> function DoClick() {");
csText.Append("Form1.Message.value='Text from client script.'} </");
csText.Append("script>");
cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
}
}
One is server side, the other is client side. They can pass variables to each other (Javascript to ASP would be via forms/querystring/cookies and ASP to JS done via response.writing variables), but they can't directly interact.
you can use page.RegisterClientScript method to do that go on the following url
http://msdn.microsoft.com/en-us/library/system.web.ui.page.registerclientscriptblock.aspx
and give it a try
Javascript is client side, c# is server side. You can't call javascript directly from C#. Take a look at Comet though, it will show you how you can push data from the HTTP server to the webpage.

Register javascript inside User Control using C#

I want to call javascript function from User Control using C#. For that i am trying to use
ScriptManager.RegisterStartupScript(this, typeof(string), "alertbox", "javascript:ShowPopup('Select a row to rate');", true);
but it is not working for me. This works fine on the page. Can some one help me out how can i call javascript function at runtime using C#.
Thanks,
Try this.GetType() instead of typeof(string):
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertbox", "ShowPopup('Select a row to rate');", true);
The following is taken from working code, showing script being registered to fire from an asynchronous postback in an UpdatePanel.
ScriptManager.RegisterStartupScript( this.upnl, this.upnl.GetType(), Guid.NewGuid().ToString(), "alert('test');", true );
If your code is not executed from inside an UpdatePanel, it still should not be typeof(string); you should use the type of some container (typically the control itself).
Type: The type of the client script block. This parameter is
usually specified by using the typeof
operator (C#) or the GetType operator
(Visual Basic) to retrieve the type of
the control that is registering the
script.
Im not sure if this is the best way to do it but for my user controls that use javascript i have a public string property on the user control and register it in the page.
// sudo code
eg.
UserControl
{
public bool CustomBool
{
get
{
//logic
return value;
}
}
public string Javascript
{
get { return "javascript...."; }
}
}
in page
{
page load()
{
if (Usercontrol.CustomBool)
{
ScriptManager.RegisterStartupScript(this, typeof(string), "alertbox", UserControl.Javascript, true);
}
}
}
The downside for this is you have to remember to register the scripts on the page. it does work though
Try it without the "javascript:" in the script string:
ScriptManager.RegisterStartupScript(this, typeof(string), "alertbox", "ShowPopup('Select a row to rate');", true);
I find that the string given is embedded literally, so it's necessary to enclose it in a suitabie <script type='text/javascript' language='javascript'> and </script>

Categories

Resources