Home » Asp.net

Call javascript function with C#

I don't know if this is the right place to post this kind of problem.

I wonder if it's impossible to call a javascript function in codebehind (C#). I have integrate Ajax on my page and I am using the updatepanel so one part of the page never do postBack. This leads to that my javascript doesn't run. I need to call it in C#.


10 Answers Found


Answer 1

You can't call javascript from inside C#, but if you need to call it after your code runs, you can.


Using the ScriptManager class, I believe the path is ScriptManager.RegisterStartUpScript.  (I say 'believe' because I have an older version of AJAX right now).

The javascript function you'll want to register is "setTimeout('MyFunctionName(param1, param2, etc.)', 100);"  What this does is it tells the page to run that function (MyFunctionName) 100 milliseconds after the page loads. Notice that the function call must be in quotes.

ScriptManager.RegisterStartUpScript(this, this.GetType(), "timeout", functionScript, True);

Answer 2

Sure you can. What you need to do is register your script in the scriptmanager's DataItem list:


this.Page).RegisterDataItem(myControl, myJavaScript);

You will then need to create a client-side script that listens for a response, gets the dataitem and fires the script:

Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(onLoading); //Hook an eventhandler to the onloading event

// Eventhandler method
onLoading(sender, args) {
     var dataItems = args.get_dataItems(); //Get all dataitems
     if(dataItems[myControlId]) {   //If this dataitem exists
           eval(dataItems[myControlId]);   //Run the script

myControlId is the ClientID of the control you used to register the DataItem with on the serverside


Answer 3

I just discovered a MUCH easier way of doing this:


.RegisterClientScriptBlock(Button1, Button1.GetType(),
"Hello", "alert('Hello World');", true);

where Button1 is a control that must be inside the UpdatePanel that caused the postback.

For some reason scriptblocks will only be registered and sent back to the client for evaluation if they come from a control in the updatepanel. This is not really cool though, since we can have other controls that cause an asyncronous postback, that want to perform the same thing. I guess this was meant for re-initializing controls on the client-side if they got re-rendered by the UpdatePanel.

If you can't live with this limitation, you have to use my first example.


Answer 4


Ok, since I want the script to run directly after the postBack ps2goat's method sounds like a better choice. (I have to much controls that updates the panel).

 I hope I get this right. In the end of a method in my C# codebehind I typed this.

 ScriptManager.RegisterStartupScript(this, this.GetType(), "timeout", "setTimeout('accordioninit()', 100);", true);

My function is accordioninit() and nothing happens. I also tried with alert(). What's wrong? It's like the method doesn't run at all.




Answer 5

It's nothing wrong with the code. I tested it without Ajax and it's works fine. Sadly it doesn't work when I update my content in the updatePanel. I also tried a simple method with a label and then changing the text in the label from serverside to "<script>myfunction()</script>" but it's the same problem, nothing happens. If I wrote the Ajax call by myself I could have added some code to call the function last of all. It must be a simple way to solve this or am I screwed?



Answer 6

ps2goat's method will only work when the page loads (ie. first page load, or full page postback).

You have to use either of my methods to fire the script during an async partial page postback.


Answer 7

I see. Now it works fine. Thanks a lot!

Answer 8


ps2goat's method will only work when the page loads (ie. first page load, or full page postback).

You have to use either of my methods to fire the script during an async partial page postback.


No, my method should work everytime.  I use the one I posted during async post backs.  Let's say a button is pushed, and an error occurs during that code.  I use the setTimeout function to call an alert() box, using the ScriptManager.RegisterStartupScript() function.

If you want to use a function with a control that isn't on the update panel, use Page.ClientScript.RegisterStartupScript(). 

This should work everytime, because you are only calling the setTimeout() function at a certain point, and not every postback.  So, when you do post back, that previous setTimeout() call is not re-registered unless you explicitly register it again.


Answer 9

I should clarify:  By 'work everytime', I mean that whenever the Page is currently posting back, which includes full- and async-post backs. It doesn't need to be the first page load (not from what I've tested). 

If you want to register a static script (i.e., called by a control event such as onchange), you can use the same methodology and add the attribute to the control's event during every Page Load.


Answer 10

thanks for your post .... it solved my problem



I need to call a JavaScript function while activating a quote from Actions menu. I tried using the onChange event of Status field; but it is not working. Can anyone please throw some light on this?



I have this javascript function in my .net :



        function AddCircle(latin, lonin, radius) 


            var R = 3956; // earth's mean radius in miles

            var lat = (latin * Math.PI) / 180; //rad

            var lon = (lonin * Math.PI) / 180; //rad

            var d = parseFloat(radius) / R;  // d = angular distance covered on earth's surface

            var locs = new Array();

            for (x = 0; x <= 360; x += 10) // 36 points per circle


                var p2 = new RadiusLatLong()

                brng = x * Math.PI / 180; //rad

                p2.Latitude = Math.asin(Math.sin(lat) * Math.cos(d) + Math.cos(lat) * Math.sin(d) * Math.cos(brng));

                p2.Longitude = ((lon + Math.atan2(Math.sin(brng) * Math.sin(d) * Math.cos(lat), Math.cos(d) - Math.sin(lat) * Math.sin(p2.Latitude))) * 180) / Math.PI;

                p2.Latitude = (p2.Latitude * 180) / Math.PI;

                locs.push(p2.Longitude + ' ' + p2.Latitude);


            document.getElementById('RadiusLongLats').value = locs;




I have  RadiusLongLats set up as so:

        <asp:HiddenField id="" runat="server" value="" /> 


Can I call this function from my c# code?  Not from a button as all the examples I've seen show.

Once I call this function, I'll access the data from the Hidden Field in c#.


For example, I have this c# code:


     protected void AddAddress(int query_id)



        radius_miles = Convert.ToDouble(this.TextBoxRadius.Text);

        //geo code the address here and return 'address.Latitude' and 'address.Longitude'//

        radius_lat = (Convert.ToDouble(address.Latitude) * Math.PI) / 180;

        radius_long = (Convert.ToDouble(address.Longitude) * Math.PI) / 180;


        (call the function here for example:)

        function AddCircle(radius_lat, radius_long, radius_miles); < ------ this is where I'd call the javascript function










Dear All,

I am working on web site automation in Visual foxpro. I have to call website Javascript fuctions through foxpro code. Please help me. I tried following but it is not working..

oBrowser = CREATEOBJECT("InternetExplorer.Application")
obrowser.Visible = .t.

I am not geeting parentwindow object... showing error.. i tried document.Script also no luck

Please help me to call JS function through foxpro code.

Thanks in advance






i have a js method i wrote myself called sumAlert(); 

i want to call it in my aspx like this, when a user clicks on a button

<asp:Button ID="Button" runat="server" Text="Submit" OnClientClick="if (confirm('WARNING! You will be unable to save again if you proceed')) sumAlert();"
                        OnClick="Button_Click" />

How can i get it to call the function if the user confirms OK?




showSelectedFile(editorId,data) {


var finalDivId = editorId + '_content';



document.getElementById(finalDivId).innerHTML =



This my javascript function.It is stored in a js file.

Now i have a usercontrol(texteditor).I want to set it's innerhtml property through function.This function must be called from code behind according to the condition


if (e.CommandName == "Select")

here is the part of asp code

content=<P>shaheeraiqbalnoormahalandone</P><P>   <IMG src="http://localhost:3032/IHSOnline/editorimages/UserImages/48cb1.bmp" width=150></P></P>P>images/UserImages/c801d.jpg" width=150></P>/UserImages/df943.JPG" width=150></P>


var data = Server.HtmlDecode(content);


if (!Page.ClientScript.IsClientScriptBlockRegistered(typeof(Page), "assignvalue"))



typeof(Page), "assignvalue", "showSelectedFile('+Texteditor1.HamEditorChildID +,+data+');", true);



asp code not calling the function showSelectedFile.Can anyone findout the mistake and help me to do this

thanks in advance



 Can you call Javascript function from the codebehind?



i am having two button controls on page i need to make button1 disable after clicking the button2 . i have written one javascript function to do button disable. but i need to call that javascript function in button2 click code behind(Serverside).My requirement is like this how should i make pls help me to solve this problem



i have javascript file 'script.js' where i have writt en a function for print. but this function is working fine if i am not using master page in my report page but the question is i want to use master page for my report page where i am calling javascript function but it is not working . Do help me regarding MasterPage and Javascript function.


When I edit single recored in page, I use checkbox to get a selected row not every row with an actionlink element, but it seemed I cant make this way happen through calling javascript code(function GetSelectedRow() should return an id). Could anyone have a nice idea?

<head runat="server">
    <script type="text/javascript" language="javascript">
        function GetSelectedRow() {
            var a = 0;
            var chkBoxes = document.getElementsByName("chkSelect");
            var count = chkBoxes.length;
            for (var i = 0; i < count; i++) {
                if (chkBoxes[i].checked == true)
                    a = chkBoxes[i].primaryKeyID;
            return a;
        <span style="width:20%">
        <%: Html.ActionLink("Add", "Create")%>
        <%: Html.ActionLink("Edit", "Edit", new { id = GetSelectedRow()) %>
        <%: Html.ActionLink("Detial", "Details", new { id = GetSelectedRow() })%>
        <%: Html.ActionLink("Delete", "Delete", new { id = GetSelectedRow()) %>
        <% foreach (var item in Model) { %>
             <%: Html.ActionLink("Details", "Details", new { id = item.AppCategoryID })%>
                    <%: Html.CheckBox("chkSelect", false, new { primaryKeyID = item.AppCategoryID })%>
                    <%: item.AppCategoryID %>
                    <%: item.AppCategoryName %>
                    <%: item.Description %>
        <% } %>



I have currently placed 5 iframes inside 5 divs and i m trying to show and hide iframes by following code

if (docid == idpath_array[1])
                document.all("div1").style.display = 'block';
                document.all("div2").style.display = 'none';
                document.all("div3").style.display = 'none';
                document.all("div4").style.display = 'none';
                document.all("div5").style.display = 'none';

but the problem is that after setting style of one div as display:none,
I am not able to display the same div latter by setting display:block hence programmically I am not able to display
an already hidden iframe by making display:block in div



I want to be able to open a new window using javascript.  I know how to do this when it's inline code but it's not too neat as the html built contains lots of reused data.

Ideally what I would like to do is, register a function using .Net then call it from my code.  It down't help that I'm not too familiar with how to pass parameters to a javascript function in the first place.

Anyone help?




Good Day all

i have used PageMethods to access the server side functions in javascript , but now my problem is that with pagemethods your controls will not go throught the full page lifecyle and these leads me to have "Object not set for an instance of an object" error. Now can someone come with a differnt approach without using pagemethods. What i want is to call a server side function , i dont want to pass any parameters to it



Hi all,

I given lot of tried to call JavaScript function get the return value but always i am getting error in namescape.

Error : Cannot find the script or external object that implements prefix 'urn:custom-javascript'.

Here is code :

Java Script function in seperate .js file.

 function findPosY(obj)
    return 123p;

--------------XSL file
<xsl:stylesheet version="1.0" 
                xmlns:asp="remove" xmlns:cc1="remove"
                exclude-result-prefixes="msxsl js"

Now calling the function.

<msxsl:script language="JavaScript" implements-prefix="js">
      function getResult (thisGuess) {
      var thisResult;
      thisResult = findPosY(document.getElementById("yahoo"));
      return thisResult;


Return Value: <xsl:value-of select="js:getResult()"/>


I am using a asp link button in grid template field which calls a pop up,i need to find the link button's control in cs page.

my link button code

<asp:LinkButtonrunat="server"ID="hlQName"Text='<%# Eval("QuestionnaireName")%>'OnClientClick="javascript:window.open('frmAssignQuestionnaire.aspx?Proj=<%#Eval("ProjectID")%>&ques=<%# Eval("QuestionnaireName")%>+','','left=250px, top=245px, width=700px, height=450px, scrollbars=no, status=no, resizable=no');return false;"></asp:LinkButton>

now i am getting server tag is not well formed error,i tried removing the quotes within eval but then i didnt get parameter values in java script.

please help this has really brought me down. 



Hi, i try to call a VB.NET function in my HTML body tag

<body onunload = "if (screenTop > 9999) call Session_End;">


Where Session is my Public VB.Net function in the Global.asax but nothing happen. Do I have to write something like "<script type=\"text/javascript\">?.




i have a javascript function that is placed in a separete file.There are some other functions also.

On a Button's OnClientClick i want to call a javascript function, but it is not called.When i put the same function in my aspx page that function is called. So how can i call that function which is placed in another .js file.

I  have taken some other controls like radio button , that is working fine when i call some functions  that is placed in the same .js file.

I have written like this in Button's OnClintClick property:





I am developing a ASP.NET ajax application.
I am using a timer:

<asp:Timer ID="Timer1" runat="server" OnTick="Timer_Tick" Interval="5000" />      

The only thing I want to do is to call a javascript function on every tick of the timer:

 protected void Timer_Tick(object sender, EventArgs e)
            ClientScript.RegisterClientScriptBlock(this.GetType(), "blink", "<script>blinkit('2');</script>");

This doesn't work.
The javascript function is being called only if I put the 'RegisterClientScriptBlock' in the Page_Load.

How can I call the javascript every couple of seconds?

Thank you


I want to initialise a text box value:

<script language="JavaScript" type="text/javascript" src="<%=ResolveUrl("~/Scripts/Common.js")%>">


<body onload="LoadDefaulteValue('revision')">

<input id="revision" type="text"  name="revision"/>

In the Common.js file, I have 2 functions:

function LoadCurrentDate(boxname) {
    var d = new Date();
    var months = new Array(12);
    months[0] = 'Jan';
    months[1] = 'Feb';
    months[2] = 'Mar';
    months[3] = 'Apr';
    months[4] = 'May';
    months[5] = 'Jun';
    months[6] = 'Jul';
    months[7] = 'Aug';
    months[8] = 'Sep';
    months[9] = 'Oct';
    months[10] = 'Nov';
    months[11] = 'Dec';
    document.getElementById(boxname).value = d.getDate() + '-' +
                                                 months[d.getMonth()] + '-' +

    function LoadDefaulteValue(boxname) {
        document.getElementById(boxname).value = 0;

When I run and got the error:

Microsoft JScript runtime error: Object expected.



i have gridview with linkbutton.when i click linkbutton it should call javascript function which returns value would be input for database functions.

how do i capture javascript function retun value(i am using Registerclientscriptblock)? and that should be input for database function.

Inshort i need to call two function from link button click - one javascript function,one ado.net function which will update value in database.

output of javascript function will be input for database function.

function Getlogitudelantitude(address)


return "35.3434343,-74.334343"


Linkbutton_click(object sender,Eventargs e)


register javascript function .. which should return value

string s = "35.34343,-74.334343"

then call database function(s) - does database operation


please reply..




I want to call javascript functions in a control,

eg. I have a button control "sl_btn",and a grid control "sl_grid",in "sl_grid" I create some "sl_btn",and I add the "sl_grid" in page.xaml, I want each button event could call some javascript function.how can I do?


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure