ASP .net get hidden value from code behind in page_load function

前端 未结 4 2097
说谎
说谎 2021-01-25 19:27

I have a hidden field that I set in my javascript code:

   

        
相关标签:
4条回答
  • 2021-01-25 19:44

    What you are missing is something along the lines of JQuery post.

    Web applications are stateless.

    As with some of the earlier posts, it is not sufficient on the server side to get the value of a control on the client without some postback event. The server has to know what is going on. In your client-side code, you get the value of the control in your script block, but there is no post to the server to let it know what transpired in the client code. You need to understand that either you post the form (or at least the data) back to the server or ,if you want this to happen without a full postback, you need to learn JQuery or Ajax.

    If you need this to happen without some user event, then do the post in the document.ready function. However, that is redundant because your server posted the data in the first place, so without user interaction (in document.ready) there isn't anything the server won't already know, especially in a hidden value.

    0 讨论(0)
  • 2021-01-25 19:49

    You are not submitting the page back to the server, you won't be able to "get" page variables unless you are doing a POST.

    change this:

    <form id="form1" runat="server">
     <div>
       <input type="text" id="Hidden1" name="Hidden1" runat="server"/>
     <div>    
    </form>
    

    to this: (EDIT: changed the type="hidden" too)

    <form id="form1" runat="server">
     <div>
       <input type="hidden" id="Hidden1" name="Hidden1" runat="server"/>
     <div>    
     <input type="submit" value="submit" />
    </form>
    

    Then click the submit button

    0 讨论(0)
  • 2021-01-25 20:02
    <form id="form1" runat="server">
       <div>
          <asp:HiddenField ID="Hidden1" runat="server"/>
      <div>    
     </form>
    
     protected void Page_Load(object sender, EventArgs e)
     {
            if ( !Page.IsPostBack)
            {
               Hidden1.Value = "Some Val";
            }
            else
            {
               string message =Hidden1.Value;
               // remaining code
            }
     }
    
    0 讨论(0)
  • 2021-01-25 20:07

    To summarize what others have written (by the looks of it) this works IF you press the submit button so that you get a postback:

    <asp:HiddenField ID="HiddenField1" runat="server" />
    <asp:Button Text="Submit" ID="btnSubmit" runat="server"/>
    <script type="text/javascript">
        document.getElementById('<%= HiddenField1.ClientID %>').value = "some value";
    </script>
    
    0 讨论(0)
提交回复
热议问题