简体   繁体   English

我如何在asp.net按钮中使用javascript变量值单击

[英]how can i use javascript variable value in asp.net button click

Given 特定

<asp:Label ID="lbldistance" runat="server"></asp:Label>

I am assigning it the value with: 我为它赋值:

var distance = response.rows[0].elements[0].distance.text;
document.getElementById('<%=lbldistance.ClientID%>').innerHTML=distance;

I want to assign lbldistance value in textbox 我想在文本框中分配lbldistance值

protected void btnValue_Click(object sender, EventArgs e)
{
    txtJSValue.Text = lbldistance.Text;
}

but when i click the btnValue, lbldistance value disappears and i don't see the value in the TextBox.. 但是当我单击btnValue时,lbldistance值消失了,并且我在文本框中看不到该值。

I am afraid you cannot do that with a label. 恐怕您不能使用标签来做到这一点。 In ASP.NET state is kept in ViewState across postback. 在ASP.NET中,跨回发状态将保持在ViewState An ASP.NET <asp:Label> is rendered into an HTML span and a span does not have ViewState . ASP.NET <asp:Label>呈现为HTML span并且span没有ViewState Therefore, when you change the innerHTML of the label, you are actually changing the innertHTML of the span tag. 因此,当您更改标签的innerHTML时,实际上是在更改span标签的innertHTML Once you press the button, the page is posted to the server where the Label is constructed and it is constructed with the initial text, NOT the one you think it should since it was changed for a span . 按下按钮后,该页面将发布到构建Label的服务器上,并且该页面是使用初始文本构建的,而不是您认为应该的文本,因为更改了span This (not keeping ViewState for a label), I think, is done for a good reason: 我认为,这样做(不为标签保留ViewState )是有充分理由的:

An HTML label should display something to the user and it is not meant to be changed by the user so there is no point in keeping the state across postback. HTML标签应向用户显示某些内容,并且不应该由用户更改,因此在回发期间保持状态是没有意义的。

To accomplish what you want, use a hidden field like this: 要完成所需的操作,请使用如下所示的隐藏字段:

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

Your javascript: 您的JavaScript:

var distance = response.rows[0].elements[0].distance.text;
// Assign distance to your label so it shows on the page
document.getElementById('<%=lbldistance.ClientID%>').innerHTML=distance;

// Assing distance to hidden field so you can get it on the server side
document.getElementById('<%=HiddenField1.ClientID%>').value = distance;

Here is how to get the value on the server side: 这是在服务器端获取值的方法:

 txtJSValue.Text = this.HiddenField1.Value;

I am not sure why you are going all the way to the server to change the Text of the txtJSValue textbox. 我不知道你为什么要一直到服务器,以改变Text的的txtJSValue文本框。 You can do that easily on the browser side the same as you are setting the label: 您可以在浏览器端轻松地完成此操作,就像设置标签一样:

document.getElementById('<%=txtJSValue.ClientID%>').value = distance;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM