56

I wrote a javascript with a asp.net page.

In Asp.net Page

<HTML> <HEAD>
     <script type="text/javascript">
      function Myfunction(){
          document.getElementId('MyText').value="hi";
      }
      </script>
</HEAD> <BODY>
<input type="text" id="MyText" runat="server" /> </BODY>

In Code-behind

 Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
  Handles Me.Load
       If Session("My")= "Hi" Then
          I want to call "Myfunction" javascript function
       End If 
 End Sub

How can I do?

2

5 Answers 5

80

One way of doing it is to use the ClientScriptManager:

Page.ClientScript.RegisterStartupScript(
    GetType(), 
    "MyKey", 
    "Myfunction();", 
    true);
5
  • 2
    Seem like the best way is yours, but what does "MyKey" is ? Sep 9, 2015 at 20:31
  • 5
    The key is just a unique identifier to help avoid emitting the same script twice. It can be anything.
    – Jacob
    Sep 10, 2015 at 15:36
  • the best solution, very simple May 11, 2018 at 13:41
  • 2
    the key shall be a GUID! Oct 23, 2019 at 13:30
  • See here if you want the javascript function to execute after the page has loaded stackoverflow.com/a/40335689/74585 Aug 25, 2020 at 8:05
44

This is a way to invoke one or more JavaScript methods from the code behind. By using Script Manager we can call the methods in sequence. Consider the below code for example.

ScriptManager.RegisterStartupScript(this, typeof(Page), "UpdateMsg", 
    "$(document).ready(function(){EnableControls();
    alert('Overrides successfully Updated.');
    DisableControls();});", 
true);

In this first method EnableControls() is invoked. Next the alert will be displayed. Next the DisableControls() method will be invoked.

0
14

There is a very simple way in which you can do this. It involves injecting a javascript code to a label control from code behind. here is sample code:

<head runat="server"> 
    <title>Calling javascript function from code behind example</title> 
        <script type="text/javascript"> 
            function showDialogue() { 
                alert("this dialogue has been invoked through codebehind."); 
            } 
        </script> 
</head>

..........

lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";

Check out the full code here: http://softmate-technologies.com/javascript-from-CodeBehind.htm (dead)
Link from Internet Archive: https://web.archive.org/web/20120608053720/http://softmate-technologies.com/javascript-from-CodeBehind.htm

2
  • 2
    Unfortunately the link is broken :-( Dec 14, 2015 at 0:23
  • Loving this solution - it almost feels like cheating. I suspect it may not be suitable for every scenario but I'm hard pressed to think of a case where it wouldn't work.
    – cymorg
    May 17, 2016 at 23:49
1

If the order of the execution is not important and you need both some javascript AND some codebehind to be fired on an asp element, heres what you can do.

What you can take away from my example: I have a div covering the ASP control that I want both javascript and codebehind to be ran from. The div's onClick method AND the calendar's OnSelectionChanged event both get fired this way.

In this example, i am using an ASP Calendar control, and im controlling it from both javascript and codebehind:

Front end code:

        <div onclick="showHideModal();">
            <asp:Calendar 
                OnSelectionChanged="DatepickerDateChange" ID="DatepickerCalendar" runat="server" 
                BorderWidth="1px" DayNameFormat="Shortest" Font-Names="Verdana" 
                Font-Size="8pt" ShowGridLines="true" BackColor="#B8C9E1" BorderColor="#003E51" Width="100%"> 
                <OtherMonthDayStyle ForeColor="#6C5D34"> </OtherMonthDayStyle> 
                <DayHeaderStyle  ForeColor="black" BackColor="#D19000"> </DayHeaderStyle>
                <TitleStyle BackColor="#B8C9E1" ForeColor="Black"> </TitleStyle> 
                <DayStyle BackColor="White"> </DayStyle> 
                <SelectedDayStyle BackColor="#003E51" Font-Bold="True"> </SelectedDayStyle> 
            </asp:Calendar>
        </div>

Codebehind:

        protected void DatepickerDateChange(object sender, EventArgs e)
        {
            if (toFromPicked.Value == "MainContent_fromDate")
            {
                fromDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
            }
            else
            {
                toDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
            }
        }
0
asp:run javascript method

Add this line to the bottom of the page before </form> tag, at least under the js function you wrote.

the reason of doning this is avoid calling your method before your browse knowing what is the funcion and finally do nothing.

<% Response.Write($"<script>yourfunction('{Config.id}');</script>"); %>

ps: I've tried all methods up there but nothing worked fine for me. And I figure out this easy and wonder way of calling js method on my own!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.