以 Javascript 正确的方式设置 asp:label 的 Text 属性

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

Set Text property of asp:label in Javascript PROPER way

javascriptasp.netlabelcode-behind

提问by splatto

I have a series of textboxes on a form. When the user inserts numbers into these textboxes, calculations are made and <asp:Label>controls are updated via JavaScript to reflect these calculations:

我在表单上有一系列文本框。当用户在这些文本框中插入数字时,会进行计算并<asp:Label>通过 JavaScript 更新控件以反映这些计算:

document.getElementById('<%=TotalLoans.ClientID %>').innerHTML = TotalLoans;

This correctly updates the UI. However, when I try to access the value in the codebehind, the Textproperty is empty. This makes sense I guess, since I was updating the innerHTMLproperty via the JavaScript.

这正确地更新了 UI。但是,当我尝试访问代码隐藏中的值时,该Text属性为空。我猜这是有道理的,因为我是innerHTML通过 JavaScript更新属性的。

//TotalLoans.Text will always be equal to "" in this scenario
double bTotalLoans = string.IsNullOrEmpty(TotalLoans.Text) 
                   ? 0.00 
                   : Convert.ToDouble(TotalLoans.Text);

How do I update the Textproperty of the <asp:Label>via JavaScript in such a way that I can read the property in the codebehind?

如何更新Text的特性<asp:Label>以这样的方式,我可以阅读代码隐藏属性通过JavaScript?

Update

更新

This is a small problem on a large form that contains 41 labels, each of which displays the results of some calculation for the user. Taking the advice of FishBasketGordo I converted my <asp:Label>to a disabled <asp:TextBox>. I'm setting the value of the new textbox as such:

这是一个包含 41 个标签的大表单上的小问题,每个标签为用户显示一些计算的结果。根据 FishBasketGordo 的建议,我将我<asp:Label><asp:TextBox>. 我将新文本框的值设置为:

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

Again, in the codebehind, the value of TotalLoans.Textis always equal to "".

同样,在代码隐藏中,的值TotalLoans.Text始终等于“”。


I don't mind changing how I approach this, but here's the crux of the matter.


我不介意改变我的处理方式,但这是问题的关键。

I am using JavaScript to manipulate the property values of some controls. I need to be able to access these manipulated values from the code behind when 'Submit' is clicked.

我正在使用 JavaScript 来操作某些控件的属性值。单击“提交”时,我需要能够从后面的代码中访问这些操作值。

Any advice how I can go about this?

有什么建议我可以怎么做吗?

Update 2

更新 2

Regarding the answer by @James Johnson, I am not able to retrieve the value using .innerTextproperty as suggested. I have EnableViewStateset to true on the <asp:Label>. Is there something else I am missing?

关于@James Johnson 的回答,我无法.innerText按照建议使用属性检索值。我EnableViewState<asp:Label>. 还有什么我想念的吗?

I don't understand why, when I type in a textbox and submit the form, I can access the value in the codebehind, but when I programmatically change the text of a textbox or label by way of JavaScript, I cannot access the new value.

我不明白为什么,当我输入文本框并提交表单时,我可以访问代码隐藏中的值,但是当我通过 JavaScript 以编程方式更改文本框或标签的文本时,我无法访问新值.

采纳答案by Pankaj

Place HiddenField Control in your Form.

将 HiddenField 控件放在您的表单中。

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

Create a Property in the Form

在表单中创建属性

protected String LabelProperty
{
    get
    {
        return hidden.Value;
    }
    set
    {
        hidden.Value = value;
    }
}

Update the Hidden Field value from JavaScript

从 JavaScript 更新隐藏字段值

<script>
   function UpdateControl() {
            document.getElementById('<%=hidden.ClientID %>').value = '12';
   }
</script>

Now you can access the Property directly across the Postback. The LabelControl updated value will be Lost across PostBackin case it is being used directly in code behind .

现在您可以直接通过Postback. 如果直接在后面的代码中使用,则Label控件更新的值将丢失PostBack

回答by Vijay Kumbhoje

This one Works for me with asp label control.

这个对我来说适用于 asp 标签控件。

 function changeEmaillbl() {


         if (document.getElementById('<%=rbAgency.ClientID%>').checked = true) {
             document.getElementById('<%=lblUsername.ClientID%>').innerHTML = 'Accredited No.:';
         } 
     }

回答by Venkata Pratap

Use the following code

使用以下代码

<span id="sptext" runat="server"></span>

Java Script

Java脚本

document.getElementById('<%=sptext'%>).innerHTML='change text';

C#

C#

sptext.innerHTML

回答by James Johnson

Instead of using a Labeluse a text input:

而不是使用Label使用文本输入:

<script type="text/javascript">
    onChange = function(ctrl) {
        var txt = document.getElementById("<%= txtResult.ClientID %>");
        if (txt){
            txt.value = ctrl.value;
        }           
    }
</script>

<asp:TextBox ID="txtTest" runat="server" onchange="onChange(this);" />      

<!-- pseudo label that will survive postback -->  
<input type="text" id="txtResult" runat="server" readonly="readonly" tabindex="-1000" style="border:0px;background-color:transparent;" />        

<asp:Button ID="btnTest" runat="server" Text="Test" />

回答by clamchoda

Since you have updated your label client side, you'll need a post-back in order for you're server side code to reflect the changes.

由于您已更新标签客户端,因此您需要回发以便您的服务器端代码反映更改。

If you do not know how to do this, here is how I've gone about it in the past.

如果您不知道如何执行此操作,以下是我过去的处理方法。

Create a hidden field:

创建一个隐藏字段:

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

Create a button that has both client side and server side functions attached to it. You're client side function will populate your hidden field, and the server side will read it. Be sure you're client side is being called first.

创建一个同时具有客户端和服务器端功能的按钮。您的客户端函数将填充您的隐藏字段,服务器端将读取它。确保您的客户端首先被调用。

<asp:Button ID="_Submit" runat="server" Text="Submit Button" OnClientClick="TestSubmit();" OnClick="_Submit_Click" />

Javascript Client Side Function:

Javascript客户端功能:

function TestSubmit() {
              try {

             var message = "Message to Pass";
             document.getElementById('__EVENTTARGET').value = message;

           } catch (err) {
              alert(err.message);

          }

      }

C# Server Side Function

C# 服务器端函数

protected void _Submit_Click(object sender, EventArgs e)
{
     // Hidden Value after postback
     string hiddenVal= Request.Form["__EVENTTARGET"];
}

Hope this helps!

希望这可以帮助!

回答by John

The label's information is stored in the ViewState input on postback (keep in mind the server knows nothing of the page outside of the form values posted back, which includes your label's text).. you would have to somehow update that on the client side to know what changed in that label, which I'm guessing would not be worth your time.

标签的信息存储在回发时的 ViewState 输入中(请记住,服务器对回发的表单值之外的页面一无所知,其中包括您的标签文本)。您必须以某种方式在客户端将其更新为知道那个标签有什么变化,我猜这不值得你花时间。

I'm not entirely sure what problem you're trying to solve here, but this might give you a few ideas of how to go about it:

我不完全确定你想在这里解决什么问题,但这可能会给你一些关于如何解决的想法:

You could create a hidden field to go along with your label, and anytime you update your label, you'd update that value as well.. then in the code behind set the Text property of the label to be what was in that hidden field.

您可以创建一个隐藏字段来与您的标签一起使用,并且无论何时更新您的标签,您都会更新该值......然后在后面的代码中将标签的 Text 属性设置为该隐藏字段中的内容.

回答by Jashwant

Asp.net codebehind runs on server first and then page is rendered to client (browser). Codebehind has no access to client side (javascript, html) because it lives on server only.

Asp.net 代码隐藏首先在服务器上运行,然后将页面呈现给客户端(浏览器)。代码隐藏无法访问客户端(javascript、html),因为它只存在于服务器上。

So, either use ajax and sent value of label to code behind. You can use PageMethods, or simply post the page to server where codebehind lives, so codebehind can know the updated value :)

因此,要么使用 ajax 并将标签的值发送到后面的代码。您可以使用PageMethods,或者只是将页面发布到代码隐藏所在的服务器,以便代码隐藏可以知道更新的值:)