Creating a hidden field in codebehind and accessing it via clientside javascript

I want to add a hidden field programmatically to an asp.net page, read and change it via javascript. So far my code fails at reading the added hidden field.

Here is a simple example:
Default.aspx:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
    <input type="hidden" id="myHiddenField1" value="blub" runat="server" />

    <button onclick="myFunction()">click me</button>
    <script>
        function myFunction() {

            var testVar = document.getElementById("myHiddenField1").value; //works: field defined in aspx page
            var testVar2 = document.getElementById("myHiddenField2").value; //fails, Object required: field defined in codebehind

            alert(testVar);
        }
    </script>
</body>
</html>

Default.aspx.cs (includes ommited):

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Page.RegisterHiddenField( "myHiddenField2", "bla!" ); doesnt work either
        Page.ClientScript.RegisterHiddenField( "myHiddenField2", "bla" );
    }
}

[edit]

The error i receive is: Microsoft JScript runtime error: Object required. If i add an alert(testVar2) and ignore the error the message box displays “undefined”.

[/edit]

[edit2]
[removed edit, since i was wrong]
[/edit2]

Summering up my question: How do i create a hidden field in codebehind so i can get and set it from javascript?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You could try something like this:

protected void Page_Load(object sender, EventArgs e)
{
    HtmlInputHidden hidden2 = new HtmlInputHidden();
    hidden2.ID = "Here you will put the id of the control";
    hidden2.Value = "Here you will put your value";
    this.Controls.Add(hidden2);
}

At the top of your source code file, you have to add this statement:

using System.Web.UI.HtmlControls;

Method 2

The main problem was that the following line was missing in the aspx page:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

The codebehind was never executed.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x