Sam
Sam

Reputation: 1343

ASP.NET undefined from hiddenfield value

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());

Upvotes: 1

Views: 1822

Answers (2)

tkarnau
tkarnau

Reputation: 160

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" />

Upvotes: 3

Imad
Imad

Reputation: 7490

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

Upvotes: 2

Related Questions