简体   繁体   中英

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.

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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM