如何在 C# 中调用 javascript 并获取返回值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9326635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:17:13  来源:igfitidea点击:

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

c#javascriptasp.net-3.5

提问by Sankar M

<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.

我如何在后面的代码中调用这个 javascript 函数并适当地处理各自的返回值。

回答by kamui

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

您可以使用以下命令轻松声明要在客户端上运行的 JavaScript

 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.

注意:我已将 JavaScript 分成多行以使其更易于阅读,但它应该都在一行上。

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.

您的问题出现在问题的第二部分,即发回数据,您很可能需要回发(部分或全部或使用 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 隐藏字段的更新面板和一个隐藏按钮来触发它,用这个函数的任何内容填充隐藏字段的值,在你的代码后面有一些代码来捕获事件。

<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
    }