Javascript 回传后在js中分配的隐藏值丢失

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6270085/
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-08-23 21:02:37  来源:igfitidea点击:

Hidden value assigned in js lost after postback

javascriptasp.netpostbackhidden-field

提问by Gonzalo

Here's my problem. I have a hidden field whose value I change through a javascript method. The problem is after postback the value is lost.

这是我的问题。我有一个隐藏字段,我通过 javascript 方法更改了它的值。问题是回发后值丢失了。

How can I persist the value after postback?

回发后如何保留该值?

Thanks!

谢谢!

.aspx File

.aspx 文件

<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:Button ID="BtnGuardar" runat="server" OnClick="BtnGuardar_Click" OnClientClick="return GridUpdateInfoOK()" />

.js file

.js 文件

document.getElementById('<%= HiddenField1.ClientID %>').value = 'TEST';

.aspx.cs file

.aspx.cs 文件

protected void BtnGuardar_Click(object sender, EventArgs e)
{
    String test = HiddenField1.Value;
}

回答by marto

You don't need to have the hidden input run at server. You can do:

您不需要在服务器上运行隐藏的输入。你可以做:

<input type="hidden" id="HiddenInput" name="HiddenInput" value="" />

Then when you post back you can access it like that:

然后当你回发时,你可以像这样访问它:

protected void BtnGuardar_Click(object sender, EventArgs e)
{
    String test = Request.Form["HiddenInput"];
}

回答by noinstance

That doesn't work like that. The value is not present since the PageLoad, so won't be postbacked. Try using a TextBox with style="display:none".

那不是那样工作的。自 PageLoad 以来该值不存在,因此不会回发。尝试使用 style="display:none" 的 TextBox。

回答by Shiblee

Please use

请用

<asp:HiddenField ID="HiddenField1" runat="server" EnableViewState="true"/>

Then we will get the value after postback.

然后我们将在回发后获得该值。

All the properties of HiddenField are as bellow:

HiddenField 的所有属性如下:

<asp:HiddenField
    EnableTheming="True|False"
    EnableViewState="True|False"
    ID="string"
    OnDataBinding="DataBinding event handler"
    OnDisposed="Disposed event handler"
    OnInit="Init event handler"
    OnLoad="Load event handler"
    OnPreRender="PreRender event handler"
    OnUnload="Unload event handler"
    OnValueChanged="ValueChanged event handler"
    runat="server"
    SkinID="string"
    Value="string"
    Visible="True|False"
/>