Friday, May 18, 2012

Read hidden field value in asp.net from jquery

Often we are confused about how to read values set in asp.net HiddenField from jquery and use the values in the web form. Many-a-times we see the threads over the asp.net forums about the difficulties associated with reading asp.net HiddenField values. I have tried to give easy and fast way to read values and set values of hidden filed in asp.net using jquery.
You may first download the latest jquery file from jquery.com.
asp.net webform - design page
<body>
    <form id=\"form1\" runat=\"server\">
    <div>
    <asp:HiddenField ID=\"HiddenField1\" runat=\"server\" />
    <asp:Label ID=\"lblSiteName\" runat=\"server\"></asp:Label>
    </div>
    </form>
    <script type=\"text/javascript\" src=\"js/jquery-1.3.2.min.js\"></script>
    <script type=\"text/javascript\">
        $(function () {
            //reading hidden field value
            var mySite = $(\'#HiddenField1\').val();
            //displaying the value in an asp.net Label control
            $(\'#lblSiteName\').html(\'My site is: \' + mySite);
            //setting value of HiddenField control
            $(\'#HiddenField1\').val(\'New site is: http://asp.net\')
        });
    </script>
</body>
asp.net webform - code page (in c#)
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            HiddenField1.Value = "http://dotnetspidor.blogspot.com";
        }
    }
Known issue
If you have put the asp.net HiddenField control below the script tags, you may end up reading 'undefined' values. To solve the issue, I recommend putting the hidden fields at the top of the page just below the form tag.
Further, if you are using asp.net Master Page, please make changes in the jquery codes respectively. In such case, I  recommend the following syntax:
var mySite=$('[id$=HiddenField1]').val();
The system $= means the value that end with HiddenField1. This works since you usually see the id HiddenFiled1 used with master page rendered as ctl00_ContentPlaceholder1_HiddenField1.

Happy programming!!
Shout it

Popular Posts

Recent Articles