简体   繁体   English

如何在asp.net 中更改label.text?

[英]How to change label.text in asp.net?

I'm trying to change a label text from cs file after I receive a message from the server.收到来自服务器的消息后,我尝试更改 cs 文件中的标签文本。 I tried using to put the label in updatepanel but couldn't make it work.我尝试使用将标签放在 updatepanel 中,但无法使其工作。 How can i update the display of the label?如何更新标签的显示?

Usually this is something along the lines of通常这是沿着

myLabel.Text = "Value";

If it's in an UpdatePanel, the rules are a little different.如果它在 UpdatePanel 中,则规则略有不同。 I think you need to get the control, then update its value.我认为您需要获得控制权,然后更新其值。 Something along the lines of:类似的东西:

Label lbl = (Label) updatePanel1.FindControl("myLabel");
lbl.Text = "Value";

If you are trying to avoid a post back, then you can use ASP.NET AJAX Page Methods to query the server via AJAX and then push the value returned into the label control, like this:如果您想避免回发,则可以使用 ASP.NET AJAX 页面方法通过 AJAX 查询服务器,然后将返回的值推送到标签控件中,如下所示:

Markup:标记:

<script type="text/javascript">
    $(document).ready(function () {
        $('.TheButton').click(function () {
            $.ajax({
                type: "POST",
                url: "Default.aspx/GetDate",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    $('.TheLabel').text(data.d);
                }
            });

            return false;
        });
    });
</script>
<asp:Label ID="Label1" runat="server" Text="Nothing" CssClass="TheLabel" />
<br/>
<asp:Button runat="server" ID="Button1" CssClass="TheButton" Text="Update Label"/>

Code-behind:代码隐藏:

[WebMethod]
public static string GetDate()
{
    return DateTime.Now.ToString();
}

Note: ASP.NET AJAX Page Methods are static methods that are not part of the ASP.NET page life-cycle.注意:ASP.NET AJAX 页面方法是static方法,不属于 ASP.NET 页面生命周期的一部分。 They do not have access to any of the controls on the page, but are very useful for getting data from the server (in this case the server time).他们无权访问页面上的任何控件,但对于从服务器获取数据(在本例中为服务器时间)非常有用。 In the interest of simplicity, I used CSS class names on the server controls to make the jQuery selectors simpler.为了简单起见,我在服务器控件上使用了 CSS 类名,以使 jQuery 选择器更简单。

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

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