0

I am trying to pass a value from a JScript function to an ASP.NET Control but I am not able to make it work. What am I doing wrong here:

aspx.cs

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication5._Default" %>

<!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">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function saveMyData() {
            var myData = "TestData";
            var hiddenInput = document.getElementById('<%=HiddenField1.ClientID %>');
            hiddenInput.Value = myData;
        }
    </script>

</head>
<body onload="javascript:saveMyData();">
    <form id="form1" runat="server">
        <div>
            <asp:HiddenField ID="HiddenField1" runat="server" />
            <br><input type="submit" value="Press Me!"><br> <--New Code
        </div>
    </form>
</body>

</html>

Code Behind:

using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace WebApplication5
{
    public partial class _Default : Page
    {
        protected HtmlInputHidden HiddenField;

        protected void Page_Load(object sender, System.EventArgs e)
        {
            string value = HiddenField1.Value;
        }
    }
}

**UPDATE**

I added in a Submit button but I am still not able to assign the myData Value to the Hidden Control, any thoughts?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Mark Kram
  • 5,672
  • 7
  • 51
  • 70

2 Answers2

0

All you're missing is a postback. You will need the page to post back before it is able to read the newly inserted value into HiddenField1. The javascript is adding the value to HiddenField1 after Page_Load.

Khan
  • 17,904
  • 5
  • 47
  • 59
0

What are you trying to do? From what it looks like, you try to read out the value you set via Javascript (on the client side), but you never actually returned the data to the server.

You wont be able to read it without a PostBack, because the javascript does not get executed on the server side.

Add a button, make a Postback and see if you can read out the data then.

magnattic
  • 12,638
  • 13
  • 62
  • 115