Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to call javascript function in aspx.cs page?
Posted

Despite of many "answers" with examples published on this site, you never really call Javascript from ASP.NET code. It will became quite obvious if you understand what happens on server side and on client side. You ASP.NET code behind works on the server side. All it does is processing the HTTP request and producing some content in HTTP response. As you ask about Javascript, this content is HTML, Javascript, and anything which can come with HTML.

What ASP.NET code does to Javascript? If generates it, perhaps having some fragments of code (usually some immediate constants, which are, from the standpoint of the ASP.NET application are variable) calculating and generating on the fly. And when the HTML page with Javascript arrives to the client side, a Web browser calls the Javascript functions, in response to events invokes in the browser, according certain rules you should know. From this moment, this code is totally agnostic to ASP.NET, as well as any other server-side technology. So, learn how Javascript works separately, without any connection to ASP.NET.

See also: http://msdn.microsoft.com/en-us/library/System.Web.UI.ClientScriptManager%28v=vs.110%29.aspx[^].

—SA
 
Share this answer
 
Comments
Nicely explained. My 5+. :)
Sergey Alexandrovich Kryukov 20-Dec-13 10:55am    
Thank you, Tadit.
—SA
The below example shows how to call a javascript function from .cs file...


C#
string script = " <script type=\"text/javascript\"> javascriptFuntion();   </script> ";

           // if not using update panel, u can use this script...
           //  this.Page.ClientScript.RegisterStartupScript(typeof(Page), "callfn", script);

           // if you are using ajax update panel use the below line of code..
           ScriptManager.RegisterStartupScript(this, typeof(Page), "callfn", script, false);
 
Share this answer
 
Refer Call Javascript function from codebehind page (Asp.Net)[^] by Sibasis.

Very nicely explained. :)
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 20-Dec-13 3:03am    
All such "explanations" have one biggest flaw: they "answer" OP's question without explaining a fundamental thing: Javascript is never ever called from a code behind page. And this is the first thing OP needs to understand. Please see my answer.
—SA
Correct. :)

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