Search code examples
c#javascriptasp.net-3.5

How to call a javascript in C# and get a return value?


<script language="javascript" type="text/javascript">
    function myjavascriptfn() 
      {
        //debugger;
        var strValue= "test";
        return strValue
      }

How do I call this javascript function in my code behind and proceed appropriately with respective of return values.


Solution

  • You can easily declare JavaScript to be run on the Client using

     ScriptManager.RegisterStartupScript(this, this.GetType(), "launchpage", "
         function javascriptfn() {
           var strValue= 'test';
           return strValue;
         }
         document.getElementById('"+HiddenField1.ClientID+"').value = javascriptfn();
         document.getElementById('"+saveProgressButton.ClientID+"').click();
      ", true);
    

    note: I have divided out the JavaScript out onto multiple lines to make it easier to read but it should all be on one line.

    Your problem comes with the second part of the question, sending the data back, you will most likely need a postback (partial or full or handle it with AJAX.

    I would add an updatepanel with a asp hiddenfield and a hidden button to trigger it, populate the value of the hidden field with whatever this function is for had have some code in your code behind to capture the event.

    <asp:UpdatePanel ID="responcetable" runat="server" UpdateMode="Conditional">
        <ContentTemplate>  
            <asp:HiddenField ID="HiddenField1" runat="server" />   
            <asp:Button ID="saveProgressButton" runat="server" Text="Button" CssClass="displaynone" /> 
        </ContentTemplate>        
        <Triggers><asp:AsyncPostBackTrigger ControlID="saveProgressButton" EventName="theeventtodealwiththis" /></Triggers>
    </asp:UpdatePanel>
    

    and on the serverside

        protected void theeventtodealwiththis(object sender, EventArgs e)
        {
             // some logic to handle the value returned
        }