Call Javascript function from C#


In this article we will discuss about calling javacript function from C#. We all know that javascript is client side language and can be called only when a client triggers an event, but what if we want to call javascript after a server process is finished, yes its possible in c#, we can call javascript after a server side coding has finished.
Inorder to javascript to work we need to register the following namespace in .cs file

Using System.Web.UI

After you have registred the System.Web.UI, then you can invoke a class ‘ScriptManager‘ which manages ASP.Net script libraries and script files, partial page rendering, and client proxy class generation for Web and application services. After invoking the ScriptManager class, we have now access to RegisterClientScriptBlock which has 5 agruments namely Control control, Type type, string key, string script, bool addScriptTags. Inshort we have the following method

void ScriptManager.RegisterClientScriptBlock(Control control, Type type, string key, string script, bool addScriptTags)

It registers a client script block with the System.Web.UI.ScriptManager control for use with a control that is inside an System.web.ui.update panel control and then adds the script block to that page.

It has the following exceptions

Now let us see the arguments called

Control control : Since we are calling javascript on page so we will require here the keyword ‘Page’.

Type type : Here we use typeof(page) which represents an .aspx file, also known as a web forms page, requested from a server that hosts an ASP.Net web application.

String key : It refers to the name you want to give to the registered client script block (Remember giving same name to more than one Registerclientscript block will break the functionality of the script and both the scripts will not work).

String script : Here you can either type the javascript or give a reference to external javascript file.

Bool AddScriptTags : This feature allows you either to enable or disable script tags. (Either true or false).

So inshort, here is the complete code for the above explanation.

ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "script", " myfunction()", true);


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CommentLuv badge