user1926138
user1926138

Reputation: 1514

How to set and get Boolean value from a asp.net hidden field

I have a hidden field. Where I need to set a Boolean value intitially. After some operation I need to update the hidden filed value using JavaScript. But we can only store string value in hidden field. How to set/get Boolean value in hidden field?

Any Idea how to implement it?

Upvotes: 6

Views: 25485

Answers (2)

User125
User125

Reputation: 108

You can use it without converting into Boolean

<asp:HiddenField ID="hf" runat="server" Value="True" />
<script type="text/javascript">
    var hf = document.getElementById('<%= hf.ClientID %>');
    if (hf.value == "True") {
        //your code
        hf.value == "False";
    } else {
        //your code
        hf.value == "True";
    }
</script>

Upvotes: 0

Mike W
Mike W

Reputation: 318

As you correctly noticed - you can only store String in HiddenField Value. To determine boolean value in Code Behind - you should Convert String Value to Bool.

For example:

bool val = Convert.ToBoolean(HiddenField1.Value);

To set Hidden Field value:

HiddenField1.Value = val.ToString();

in JavaScript - you can accomplish this by using:

var hiddenFieldValueString = document.getElementById("HiddenField1").value;
var val = (hiddenFieldValueString === "true");

setting new Hidden Field Value:

document.getElementById("HiddenField1").value = val;

Upvotes: 8

Related Questions