Home > Software design >  how to store a label control text into a textbox control value using javascript
how to store a label control text into a textbox control value using javascript

Time:05-17

i am trying to set the value of a textbox control in my aspx page as the value of a label text. I am using the following code but nothing happens. I have tried from the code behind file using c# and then I want to assign the textbox value to a session variable. If I just assign a string value like "Hello"it works, but otherwise nothing works.

So this is the markup:

         <asp:Label ID="blbtest" runat="server" ClientIDMode="Static"> 
         </asp:Label>
         <asp:Button ID="btnBook" runat="server" Text="Book Now" 
          CssClass="spaces-info__button" OnClick="btnBook_Click"/>
    
         <asp:TextBox ID="txtmtcid" runat="server"> 
         </asp:TextBox>

Code behind:

   protected void Page_Load(object sender, EventArgs e)
    {
        

        if (!(Session["username"] == null))
        {
            string usn = Session["username"].ToString();
            lblusn.Text = usn;      
        }

    }
 protected void btnBook_Click(object sender, EventArgs e)
    {
        txtmtcid.Text = blbtest.Text;
        Session["mtcid"] = txtmtcid.Text;
        Response.Redirect("booknow.aspx");
    }

updated js:

    $(function () {
    //dom is ready
var request = new XMLHttpRequest;
var usn = document.getElementById('lblusn').innerHTML;

console.log(usn);

request.open('GET', "URL"   usn   ""); //of course I have replaced 
    the URL here
    request.onload = function () {
    var response = request.response;
    var parsedData = JSON.parse(response);
    console.log(parsedData);
    var nm = parsedData.fullName;
    document.getElementById('lblfullnm').innerHTML = nm;
    var mtcid = parsedData.employeeCode;
    document.getElementById('blbtest').innerHTML = mtcid;
    document.getElementById('txtmtcid').value = 
 document.getElementById('blbtest').innerHTML
};
request.send();
    });

I am new to js, and asp.net, so trying to browse whatever possible and work things out here. The session variable value is just not getting passed to next page. Honestly, i dont need the textbox, I dont know if label text can be stored in session variables. If thats possible, then all I want to do is assign the blbtest label text to the session variable, but that also didnt work,but if I am hard coding it like:

    Session["mtcid"]="D-11234" 

this works and the value of session variable is passed.

hence I am trying now with textbox. Please let me know if theres a better approach to this.

If there is a way to avoid the use of the label and textbox and simply pass the session variable, Session["username"] from the code behind to the javascript, that would be great. how can I do it?

This was my previous post, I am reposting since I didnt recive much help. I realised that on button click, the values in the label controls and the Session variable are getting lost, how can I deal with this?

CodePudding user response:

Ok, lets take a whack at this again.

Honestly, i dont need the textbox, I dont know if label text can be stored in session variables

Ok, then it is in session, so the next page you jump to does not care, or have to know anything about the current page, right? If the value is ALEADY in session, then why do we care about this current page?

And what's the goal with your posted js routine? That looks like a web method call? Why, and what is that supposed to do?

And why is usn being passed with that "post" routine to the server when we already admitted that the server session has this value?

The code behind can freely use that session() value, so why then is that usn being passed to some server side routine? I don’t grasp the goal here. Perhaps you calling some web method, but the web method has use of session, so this begs the question why usn is being passed in that url and web method? Why???

I dont know if label text can be stored in session variables

It certainly can can be. But the $100 question is DOES the client side code in the page EVER need to use that value? That really is the question here. If it does, then you can place that value into a label, text box, or MORE common is to use a hidden field control. (they all can be used - but if you not look to display that value on the page, then you could I suppsoe "hide" the label, or text box (style="display:none"), but hidden field would be better since it is already hidden.

So, the ONLY reason to send and place that session() value into the client side markup would be if local js code (as opposed to server side code) needs that value.

Since the value is in session(), then ANY kind of navigation to any other page? It can use that value in session(). You have zero need to pass the value in some URL parameters or whatever.

So, it not clear if this value is required client side. I guess, I have to assume some place, and some where that value is required for use in client side js code.

Or, maybe the client side code needs to CHANGE this value, and then that value needs to be passed to the next page?

So, if we need to use/see/have that session value client side?

Well, ok, then say we have this simple markup:

3 buttons. One to show the label value as is.

One button to CHANGE the label value (100% client side code).

And a 3rd button you can click, that will take this (possbile) label value, and shove it back into session.

Perhaps you not grasping the difference between client side code, and server side?

Anyway, so we have this (and I am using jQuery - it usually installed by default, and it does make referencing of client side controls a whole lot easer. (and it should be installed by default for your project).

So, here is our markup:

         <asp:Label ID="blbtest" runat="server" ClientIDMode="Static"> 
         </asp:Label>
        <br />

        <asp:Button ID="cmdShow" runat="server" Text="Show label value - client side code"
            OnClientClick="showlvalue();return false" CssClass="btn"
            />
        <br />

        <asp:Button ID="cmdchange" runat="server" Text="change client side label value"
            OnClientClick="changevalue();return false" CssClass="btn"
            />
        <br />

        <asp:Button ID="cmdJump" runat="server" Text="Jump to next page with modifed lable into session" OnClick="cmdJump_Click" />

        <script>

            function showlvalue() {
                alert($('#blbtest').text())
            }

            function changevalue() {
                var sNew = prompt("enter new value for label")
                $('#blbtest').text(sNew)
            }

        </script>

And our code behind is this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["FunTest"] = "this is session";
            blbtest.Text = Session["FunTest"] as string;
        }
    }

    protected void cmdJump_Click(object sender, EventArgs e)
    {
        // take lable value - shove back into session
        Session["FunTest"] = blbtest.Text;
        Response.Redirect("WebForm2.aspx");
    }

So, now we have this:

enter image description here

Ok, lets click on first button, we get this:

enter image description here

Now, lets click on the 2nd value, change the label (but, it ONLY occurring client side)

enter image description here

so, above "zoo zoo zoo", when I hit ok, it will shove that result BACK into the label. (but it STILL NOT in the session() yet).

we now have this:

enter image description here

So, at this point, the browser and this markup is still 100% client side - we have NOT interacted with the server. And we have to be carefull, since any standard button click WILL trigger the page load event EACH time, and THEN run your code stub. However, we have that all imporant !IsPostBack code test and stub - it is critical to have that code stub, and 99% of all my pages use that code stub for setup. If I don't use that ispostback check, then when we click the 3rd button above, the page load event fires FIRST and THEN our button event. So, page load ALWAYS triggers for each server side post-back and button event (or any other event).

So, at this point we changed the label - client side code. Now, we can click our 3rd button - the server side button.

Note how it takes the value from the label, shoves BACK into session(), and THEN we jump to the next page in queston. that target page of course can now use session(), since we moved/shoved/transfered the value in the label back into session.

And be carefull. What happens if our button on the client side is a hyper link, or navagates to the 2nd (target) page in place of server side code? Well, then our label value will NEVER make it back into session, since we MUST have a post-back in the current page. the curren page tavels back up to server, code behind runs (transfer lable back into sesson(), and THEN we execute a response.redirect to the next page.

Obviously in above, we can't jump to the next page without a post back.

However, can we work and do this 100% without ANY controls on the page, and without that label value?

sure, we can add web methods to the page. We can write a web method to get that sesson value. and we can even write a web method to modify the session() value if we want.

Note that as I suggested, since that label should be hidden, then I suggest dropping in a asp.net hidden field - they are both client side and server side friednly, and are hidden for you.

But, for jQuery, keep in mind:

 for TextBox  - use .val() to get (or set a text box)
 for Label - use .text() to get (or set a label)
 for hidden field, use .val()

and our target page - that we jump to based on hitting 3rd button, it can display that session value in a label.

Say this markup:

    <div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>

And code behind for 2nd page

   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["FunTest"] == null)
            {
                // sesson not passed, so lets jump back to page 1
                Response.Redirect("WebForm1.aspx");
            }
            else
            {
                Label1.Text = Session["FunTest"] as string;
            }
        }

    }

CodePudding user response:

my script now : <asp:Label ID="lblusn" runat="server" ClientIDMode="Static" style="display: none;"></asp:Label>

     <script src="Scripts/script.js"></script>

  <asp:HiddenField ClientIDMode="static" ID="hiddenmtcid" runat="server" />

  <section>
    <div >
        <div >
            <div >          
                
                <h2><asp:Label ID="blbtest" runat="server" 
    ClientIDMode="Static" style="display: none;"></asp:Label>
                    <asp:Label ID="lblfullnm" runat="server" 
    ClientIDMode="Static"></asp:Label>
                </h2>

Code behind:

    namespace LRC_Spaces_Booking_System
    {
    public partial class userdashboard : System.Web.UI.Page
     {
    

    protected void Page_Load(object sender, EventArgs e)
    {

        //if (!(Session["username"] == null))
        //{
        //  lblusn.Text = Session["username"].ToString();
        //}
            
        if (!IsPostBack)
        {
                if (Session["username"] == null)
                {
                    // sesson not passed, so lets jump back to page 1
                    Response.Redirect("userlogin.aspx");
                }
                else
                {
                    lblusn.Text = Session["username"] as string;
                    Session["mtcid"] = blbtest.Text;

                }
            
        }
        

    }

    protected void btnBook_Click(object sender, EventArgs e)
    {

        //lblusn.Text = hiddenusn.Value;
        //Session["mtcid"] = hiddenmtcid.Value; 
        //Response.Redirect("booknow.aspx");        
        //// take lable value - shove back into session
        
        Response.Redirect("booknow.aspx");
    }
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        GridView1.DataBind();
    }


}

Javascript:

        $(function () {
      //dom is ready
      var request = new XMLHttpRequest;
      var hiddenusn = document.getElementById('lblusn').innerHTML;
      
      request.open('GET',"https://qr.mtc.edu.om/api/public/hrmsInfo/qZ3sDDUVdhvhFQgF5XSVeJPsPp3Hvy9E/"   hiddenusn   "");
    request.onload = function () {
    var response = request.response;
    var parsedData = JSON.parse(response);
    console.log(parsedData);
    var nm = parsedData.fullName;
    document.getElementById('lblfullnm').innerHTML = nm;
    var mtcid = parsedData.employeeCode;
    document.getElementById('blbtest').innerHTML = mtcid;
    
    //console.log(document.getElementById('hiddenmtcid').value);
  };
  request.send();
  });
  • Related