ASP.NET undefined from hiddenfield value

1.7k views Asked by At

I'm trying to get the value from a hiddenfield but I'm getting an undefined alert. What am I doing wrong?

// Masterpage
...
<body>
    <div class="container">
        <asp:ContentPlaceHolder ID="MasterContent" runat="server"></asp:ContentPlaceHolder>
    </div>
    <script>
        $(document).ready(function () {
            alert($('#hiddenPersonId').val());
        });
    </script>
</body>

// Default.aspx
<asp:Content ID="Content" ContentPlaceHolderID="MasterContent" runat="Server">
    <asp:HiddenField ID="hiddenPersonId" runat="server" Value="1" />
</asp:Content>

I tried other solutions but these are also not working:

alert($("#<%= hiddenPersonId.ClientID %>").val());
2

There are 2 answers

0
Imad On BEST ANSWER

It will not work from master page. You need to call it from Default.aspx or try

 $('[id*="hiddenPersonId"]')

on master page but other pages that uses this master page should not have any control that contains hiddenPersonId in its id

2
tkarnau On

You could try setting ClientIDMode to static if you're .net 4+. You'll want to check that it is defined first. If you want/need the js to be on master page.

<script type="text/javascript">
        $().ready(function () {
            alert($('#hdnPersonId').val());
        });
</script>
<asp:HiddenField ID="hdnPersonId" Value="1" runat="server" ClientIDMode="Static" />