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

孤人 提交于 2019-12-02 14:41:14

问题


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>

`


回答1:


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>



回答2:


Your <input> tag needs a name attribute, or it won't be posted.




回答3:


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();"/>


来源:https://stackoverflow.com/questions/6997810/how-to-pass-variable-from-jquery-to-code-behind-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!