【问题标题】:passing variable from VB function to client side javascript将变量从VB函数传递到客户端javascript
【发布时间】:2012-06-18 12:56:06
【问题描述】:

您好,我正在使用此 Page.ClientScript.RegisterStartupScript() 从后面的 vb 代码调用 javascript 函数,这对我来说很好用 我的问题是如何将变量从后面的代码发送到 javascript 函数这是什么到目前为止我已经尝试过:

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
   Handles Me.LoadComplete
    Dim Myname As String = "myName"
    Dim cstype As Type = Me.GetType()
    Page.ClientScript.RegisterStartupScript(cstype, "MyKey", "hello(Myname);",
  True)

End Sub 

javascript:

   <script type="text/javascript">
    function hello(name) {
        alert("hello world from javascript " + name)
    }
</script>

谢谢...

【问题讨论】:

    标签: c# javascript asp.net .net vb.net


    【解决方案1】:

    你必须使用正确的引号来传递字符串:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
       Handles Me.LoadComplete
        Dim Myname As String = "myName"
        Dim cstype As Type = Me.GetType()
        Page.ClientScript.RegisterStartupScript(cstype, "MyKey", "hello('" & Myname & "');",
      True)
    
    End Sub 
    

    注意变量名的单引号。

    在客户端和服务器端代码之间双向传递数据的另一种方式是隐藏字段,例如

    <asp:HiddenField ID="xhidMyname" runat="server" />
    

    或

    <input type="hidden" id="xhidMyname" runat="server" />
    

    这个字段可以通过它的“value”属性在客户端和服务器端访问。

    【讨论】:

      【解决方案2】:
      Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
         Handles Me.LoadComplete
          Dim Myname As String = "myName"
          Dim cstype As Type = Me.GetType()
          Page.ClientScript.RegisterStartupScript(cstype, "MyKey", "hello('"&Myname&"');",
        True)
      
      End Sub 
      

      【讨论】:

      • 是的,对不起,我错过了在字符串周围添加单引号
      猜你喜欢
      • 2015-03-03
      • 2011-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多