Click here to Skip to main content
15,881,687 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I want to call javascript function from my asp.net code behind page
I have written following code but it is not working

XML
System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append(@"<script language='text\javascript'>");
        sb.Append(@"BlitzMap.setMapFromKML(document.getElementById('kmlString').value);");
        sb.Append(@"</script>");
        System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "JCall1", sb.ToString(), false);


can anyone tell me whats wrong with this code.
Posted
Comments
[no name] 4-May-13 8:12am    
"it is not working" is not at all a helpful description of any kind of a problem. Does your script exist at the time you are trying to call it?
sagmali 5-May-13 22:29pm    
Yes it is
Sergey Alexandrovich Kryukov 11-Jun-13 20:00pm    
There are no calls from ASP.NET to JavaScript, ever. Please see my comment to Solution 1.
—SA

Javascript executes in the browser, the codebehind on the server - so actually calling the javascript code from the codebehind would involve a lot of trickery.

I suspect that this isn't really what you attempt to do, you just want something to execute once the document is fully loaded.

If that is the case you could add something like this:
window.onload = function ()
 {
  // Your code goes here...
 };

to your javascript code.

Best regards
Espen Harlinn
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 11-Jun-13 19:59pm    
I would say in in more certain way — there is no a call. OP should understand that ASP.NET just handles HTTP request and produce HTTP response, which can be anything, including JavaScript and HTML+JavaScript. In this scenario (there used to be more unusual server-side JavaScript I don't count), all the JavaScript calls are started from a browser.
—SA
Espen Harlinn 12-Jun-13 16:04pm    
It's coming: http://www.w3schools.com/html/html5_serversentevents.asp
Sergey Alexandrovich Kryukov 12-Jun-13 16:35pm    
Good to know... :-)
—SA
Write your javascript function in head section of your page as you normally do,


C#
<head>

<script type="text/javascript">
yourfunction()

{}
</script>

</head>


and then call it from codebehind like this:

Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", yourfunction(), false);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900