How to get the text from <input hidden> in code-behind?

半世苍凉 提交于 2019-12-11 19:23:59

问题


My second question today. I got really stuck. Ok, I have two fields in an aspx file:

<input type="text" id="tbName" runat="server"/> 
<input type="hidden" id="hfName" runat="server"/>

The idea is to use text from textbox "tbName" as a parameter for my stored procedure. I decided to add its text to a hidden field "hfName" using javascript:

document.getElementById("<%= hfName.ClientID %>").value = document.getElementById("<%= tbName.ClientID %>").value;
alert(document.getElementById("<%= hfName.ClientID %>").value);

It works well and hidden field takes the text from the textbox, the function alerts about it. I use hidden field because this is the only way for me to save the text during postback.

In code-behind I try to get hidden value from hfName.Value back to the textbox, but it returns empty line:

tbName.Value = hfName.Value;

So how not to lose the textbox text and use it as a parameter? Maybe there is an easier way? I don't know jquery.


回答1:


In the main Page_Load procedure I put tbName.Value = hfName.Value; This is the only place where I try to use value from hidden field hfName.Value. tbName is not modified after it and should show the text from hidden field hfName. It doesn't.

when page loading nothing set as textbox text, so tbName and hfName values are empty.

you can test this by set default values to both hidden and text fields

<input type="text" id="tbName" runat="server" value ="txtVal"/> 
<input type="hidden" id="hfName" runat="server" value ="hftVal"/>

now on page load you can get non empty values of both controls

protected void Page_Load(object sender, EventArgs e)
{
    var txtVal = tbName.Value;
    var hfVal = hfName.Value;
}



回答2:


In your JavaScript part you write the value from tbName to hfName, in the code behind from hfName to tbName.

hfName.Value = tbName.Value;

With jQuery you could solve the client side part like

$("#<%= hfName.ClientID %>").val($("#<%= tbName.ClientID %>").val());
alert($("#<%= hfName.ClientID %>").val());


来源:https://stackoverflow.com/questions/16141847/how-to-get-the-text-from-input-hidden-in-code-behind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!