简体   繁体   中英

How to pass variable from jquery to code behind (C#)?

Here is my code, but it doesn't work (code behind gets empty string): `

<head id="Head1" runat="server">
<title>Pass Javascript Variables to Server</title>
     <script type="text/javascript">             // Second Step
         function f() {
             $("[id$='inpHide']").val("My JavaScript Value");

         }
    </script>
</head>

<body onload="SetHiddenVariable()">
    <form id="form1" runat="server">
    <div>  
        <input id="inpHide" type="hidden" runat="server" />  
        <asp:Button ID="btnJSValue" Text="Click" runat="server" OnClientClick="f"/>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>

`

There were couple of issues in your code. The parenthesis were missing while calling f function in onClientClick and if the element has id you can just use the id to select it with #

<head id="Head1" runat="server">
<title>Pass Javascript Variables to Server</title>
     <script type="text/javascript">             // Second Step
         function f() {
             $("input[id*='inpHide']").val("My JavaScript Value");
         }
    </script>
</head>

<body>
    <form id="form1" runat="server">
    <div>  
        <input id="inpHide" type="hidden" runat="server" />  
        <asp:Button ID="btnJSValue" Text="Click" runat="server" OnClientClick="f()"/>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>

您的<input>标记需要name属性,否则将不会发布。

The response from Sean McMillan is right, but I think you also need to change this :

<asp:Button ID="btnJSValue" Text="Click" runat="server" OnClientClick="f"/>

to

<asp:Button ID="btnJSValue" Text="Click" runat="server" OnClientClick="f();"/>

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