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

user1926138 picture user1926138 · Jan 5, 2015 · Viewed 19.1k times · Source

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?

Answer

Mike W picture Mike W · Jan 5, 2015

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;