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

时间:2012-02-17 10:31:55

标签: c# javascript asp.net-3.5

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

如何在我的代码中调用此javascript函数并适当地使用相应的返回值。

1 个答案:

答案 0 :(得分:3)

您可以使用

轻松声明要在客户端上运行的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);

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

你的问题来自问题的第二部分,发回数据,你很可能需要回发(部分或全部或用AJAX处理它。

我会添加一个带有asp隐藏字段和隐藏按钮的updatepanel来触发它,用这个函数填充隐藏字段的值,在你的代码后面有一些代码来捕获事件。

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

并在服务器端

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