How to call javascript function from code-behind

Javascriptasp.net

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

One way of doing it is to use the ClientScriptManager:

Page.ClientScript.RegisterStartupScript(
    GetType(), 
    "MyKey", 
    "Myfunction();", 
    true);
       

Solution 2 - Javascript

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.

Solution 3 - Javascript

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</s> (dead)
Link from Internet Archive: https://web.archive.org/web/20120608053720/http://softmate-technologies.com/javascript-from-CodeBehind.htm

Solution 4 - Javascript

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();
            }
        }

Solution 5 - Javascript

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzanhtetView Question on Stackoverflow
Solution 1 - JavascriptJacobView Answer on Stackoverflow
Solution 2 - JavascriptDeepak KothariView Answer on Stackoverflow
Solution 3 - JavascriptevaaggyView Answer on Stackoverflow
Solution 4 - JavascriptMax Alexander HannaView Answer on Stackoverflow
Solution 5 - Javascript皮皮shrimpView Answer on Stackoverflow