I have a hidden field that I set in my javascript code:
<script type="text/javascript">
function start() {
document.getElementById('Hidden1').value = "somme value";
}
</script>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="Hidden1" name="Hidden1" runat="server"/>
<div>
</form>
In my code behind I want to get the input value in my page_load function:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.ClientScript.IsClientScriptBlockRegistered("start") && !IsPostBack)
{
Page.ClientScript.RegisterStartupScript(typeof(Page), "start", "start();", true);
}
string message =Hidden1.Value;
}
The message is empty, how can'I get the hidden value in my page_load?
Thanks.
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
}
}