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

蓝咒 提交于 2019-12-02 04:21:02

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

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>

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.

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