如何填充 Label.Text - 通过 jQuery 的属性

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

How to fill a Label.Text - Property via jQuery

asp.netjquerylabel

提问by AGuyCalledGerald

I use ASP.NET and have a label control on my page, which I fill with the jQuery-Command

我使用 ASP.NET 并在我的页面上有一个标签控件,我用 jQuery-Command 填充它

$('#<%= myLabel.ClientID %>').html(content);

.val() does not seem to work with this.

.val() 似乎不适用于此。

Somehow, I have Problems getting the content in code-behind. In the code, the myLabel.Text-Property is still empty.

不知何故,我在获取代码隐藏内容时遇到了问题。在代码中,myLabel.Text-Property 仍然是空的。

回答by Nick Craver

If you want to display the value on the client and have it available on the page, you need an input that'll get sent to the code-behind when you POST like this:

如果您想在客户端上显示该值并使其在页面上可用,您需要一个输入,该输入将在您 POST 时发送到代码隐藏,如下所示:

$('#<%= myLabel.ClientID %>').html(content);
$('#<%= myInput.ClientID %>').val(content);

<asp:Label Id="myLabel" runat="server" />
<asp:HiddenField ID="myInput" runat="server" />

In the code-behind:

在代码隐藏中:

myInput.Value

回答by KP.

I think your problem is that labels (rendered as spantags) are inherently read-only in the asp.net world. They're not meant to be used as 'input' controls, and as such changes to their HTML on the client-side are ignored on the server-side, where values are set based on ViewState.

我认为您的问题是标签(呈现为span标签)在 asp.net 世界中本质上是只读的。它们不打算用作“输入”控件,因此在客户端对其 HTML 的更改在服务器端会被忽略,其中值是基于 ViewState 设置的。

To do what you are asking, you'd have to notify the server of the change as well, such as by using AJAX. The only issue here is ajax webmethods in your code behind are static, and because of this can't access the page's control set to change the .Text value.

要执行您的要求,您还必须将更改通知服务器,例如使用 AJAX。这里唯一的问题是代码中的 ajax webmethods 是静态的,因此无法访问页面的控件集来更改 .Text 值。

In the end the easiest option is to make use of hidden fields as Nick said. These are technically 'input' controls and their values changed on the client-side are sent to the server as you desire. You'd just have to keep the label/span and hidden field/input synchronized on the client.

最后,最简单的选择是利用尼克所说的隐藏字段。这些是技术上的“输入”控件,它们在客户端更改的值会根据您的需要发送到服务器。您只需要在客户端上保持标签/跨度和隐藏字段/输入同步。

Hope this helps.

希望这可以帮助。