简体   繁体   中英

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?

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM