javascript 如何从asp.net隐藏字段设置和获取布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27775811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:58:28  来源:igfitidea点击:

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

javascriptasp.nethidden-fieldboolean-operations

提问by user1926138

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?

我有一个隐藏字段。我需要最初设置布尔值的地方。一些操作后,我需要使用 JavaScript 更新隐藏的字段值。但是我们只能在隐藏字段中存储字符串值。如何在隐藏字段中设置/获取布尔值?

Any Idea how to implement it?

任何想法如何实施它?

回答by Mike W

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.

正如您正确注意到的那样 - 您只能将 String 存储在 HiddenField Value 中。要确定代码隐藏中的布尔值 - 您应该将字符串值转换为布尔值。

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:

在 JavaScript 中 - 您可以使用以下方法完成此操作:

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

setting new Hidden Field Value:

设置新的隐藏字段值:

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

回答by User125

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>