24

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:

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

This correctly updates the UI. However, when I try to access the value in the codebehind, the Text property is empty. This makes sense I guess, since I was updating the innerHTML property via the 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 Text property of the <asp:Label> via JavaScript in such a way that I can read the property in the codebehind?

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:

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

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


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.

Any advice how I can go about this?

Update 2

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

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.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
splatto
  • 3,159
  • 6
  • 36
  • 69
  • 2
    It might not be possible because an `asp:Label` isn't a type of ``. I feel like I've run into this before and had to use hidden inputs for the server to recognize it. – Greg Apr 12 '12 at 17:21
  • 2
    What you are doing will work after a postback occurs. Asp.net/Server doesn't know if anything changed until it gets another chance to look at it. – Khan Apr 12 '12 at 17:22
  • Although you could possibly make them work, `` controls aren't really the right choice for what you're doing. I would consider using a read-only textbox or something more semantically appropriate. – FishBasketGordo Apr 12 '12 at 17:38
  • Thanks FishBasketGordo, please see update – splatto Apr 12 '12 at 18:31
  • @splatto: Updated my answer. I think I've found a good solution for you. – James Johnson Apr 12 '12 at 19:19

7 Answers7

18

Place HiddenField Control in your Form.

<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

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

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

Pankaj
  • 9,749
  • 32
  • 139
  • 283
  • @James Johnson, I tried to post this on your answer. I am not able to retrieve the value using .innerText property. I have `EnableViewState` set to true on the ``. Is there something else I am missing? – splatto Apr 12 '12 at 18:39
  • I cannot access the Label updated value across `Postback` as it will be lost during postback. So, I need to use `ViewState/HiddenField` Control. – Pankaj Apr 12 '12 at 18:41
  • 1
    @PankajGarg: You were actually right. I was thinking that the value could be stored in an attribute of the label, but it is not. – James Johnson Apr 12 '12 at 18:44
  • 1
    @John: I did make a mistake regarding the label, but being that I'm in the top 0.001% of ASP.NET users on the site, I don't think it's fair to say that I have no understanding of ASP.NET. I appreciate your comment though :) – James Johnson Apr 12 '12 at 18:51
  • This solution works great. However, actually selecting an ASP.NET hidden field can be a problem with an external JavaScript file and jQuery. [This answer](http://stackoverflow.com/questions/8908340/get-the-value-of-an-asphiddenfield-using-jquery#8908356) has the solution to that. – NightOwl888 Apr 17 '15 at 18:55
5

This one Works for me with asp label control.

 function changeEmaillbl() {


         if (document.getElementById('<%=rbAgency.ClientID%>').checked = true) {
             document.getElementById('<%=lblUsername.ClientID%>').innerHTML = 'Accredited No.:';
         } 
     }
Vijay Kumbhoje
  • 1,401
  • 2
  • 25
  • 44
3

Use the following code

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

Java Script

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

C#

sptext.innerHTML
2

Instead of using a Label use a text input:

<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" />
James Johnson
  • 45,496
  • 8
  • 73
  • 110
  • 1
    Although it solves the OP's problem it causes another one. The text input can be selected by the mouse. This gives the appearance the field is updatable. Then if the backspace button is clicked, IE navigates to the previous page. Farewell to the data that was in the form. – NightOwl888 Apr 17 '15 at 18:50
1

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:

function TestSubmit() {
              try {

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

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

          }

      }

C# Server Side Function

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

Hope this helps!

clamchoda
  • 4,411
  • 2
  • 36
  • 74
1

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.

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 :)

Jashwant
  • 28,410
  • 16
  • 70
  • 105
0

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.

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.

John
  • 17,163
  • 16
  • 65
  • 83