How do I get text of label when changed to server side? - javascript

I'm trying to assign the text of a label to a hidden field when not post back but I fail. This is what I done.
If Not IsPostBack Then
Dim structPayperiod As strcPayperiodDet
structPayperiod = objTimeSystem.getCurrentPayPeriod()
hdnPayperiodseq.Value = structPayperiod.Payperiodid
hdnPayPeriodStartDt.Value = structPayperiod.startdate.ToString
lblPayPeriodStartDt.Text = structPayperiod.startdate
displayPayrollIdOrgs(objTimeSystem.getPayrollIDOrgs())
grd_Employees.Visible = False
RptErrorsMessages.DataSource = objTimeSystem.getErrorMessages()
RptErrorsMessages.DataBind()
Else
hdnPayPeriodStartDt.Value = lblPayPeriodStartDt.Text.ToString
End If
Problem comes in else clause where the value doesn't get update with new label value. lblPayPeriodStartDt.Text is not updating.
The value of label is date and it updates every time I change the date using calender control on client side. But, the value of the label doesn't refresh with that value.
<asp:Label ID="lblPayPeriodStartDt" runat="server"></asp:Label>
<img src="../Images/calendar.gif" class="clsCursorHand" alt="" title="Select Pay Period"
onclick="Javascript:PayPeriodsPayroll('<%=lblPayPeriodStartDt.ClientId %>',event);"/>

You are not going to get the value of the <asp:Label you modified on client side at the code behind. If I'm correct ASP.NET label is rendered as a span element in the client side:
I think that only the controls that are rendered as input controls and values changed at client side are updated on viewstate, so your only resort is to stick to the hidden field.
You just have to do the other way around.
1.Pass the hidden field to the js function and update the value of the hidden field at the client side in your js function PayPeriodsPayroll like below
function PayPeriodsPayroll (hdnObj)
{
var hdnPayPeriod = document.getElementById(hdnObj);
hdnPayPeriod.val('the value you want to set');
}
Then in your pageload
If Not IsPostBack Then
....
Else
// update label with the hidden field value if you need it
lblPayPeriodStartDt.Text = hdnPayPeriodStartDt.Value
End If

surely you are not posting back to the server every time you change the date in the calendar control.
You can do a postback to the server from javascript using the __doPostback() function.
see this link:
__doPostback function example

Related

assigning value to hidden field from javascript

I am trying to do what seems to be simple but am unable to accomplish
I am trying to set the value of a column after a row focus change in a grid to a hidden value in java script.
My imbedded javascript code:
function OnGridFocusedRowChanged() {
grdA.GetRowValues(grdA.GetFocusedRowIndex(), 'ClientID', OnGetRowValues);
}
function OnGetRowValues(values) {
//Set hidden value
document.getElementById('<%=hdnClientID.ClientID%>').value = values[0];
//Fire button click
btnPopulateGrids_Click();
}
where hdnClientID is the name of my hidden field
In GridA I have the setting as such that OnGridFocusedRowChanged gets executed each time a row focus change takes place.
To this point, it works fine, the values[0] in OnGetRowValues() contains the correct value from the corresponding row in GridA.
But in the corresponding code behind, I cannot access the value from hidden field hdnClientID. Always comes up null when accessing
Current_Client_ID = CInt(hdnClientID.Value);
cannot access or convert any value from
hdnClientID.ClientID.
either.
I'm missing something simple.
I had to complete a similar task recently and I too was unable to access the value from codebehind. I researched and found out that it is not that simple and that you can't do it with javascript. What I would recommend is to check if you have jQuery installed and if you do, change your function to this:
function OnGetRowValues(values) {
//Set hidden value
$('#<%=hdnClientID.ClientID%>').val(values[0]);
//Fire button click
btnPopulateGrids_Click();
//If you change your HiddenField to have OnValueChange event, you can trigger it with this
//__doPostBack('<%= CompanyCode.ClientID %>', '');
}
Also, I guess you are firing some function from code behind with btnPopulateGrids_Click();.
I would recommend adding OnValueChanged="hdnClientID_OnValueChanged"/> to your <asp:HiddenField/> and using my supplied function triggering method.

access local storge with javascript and C#, asp.net

i am hoping someone will help me, i am pulling out my hair for the last few hours...!
I am using asp.net web forms with c#
I have the following button in my menu , this button opens up a page that lists selected properties for realtor…
htmlCode.Append("<button type='button' class='btn btn-basic' id='btnEnquire' onclick='openEnquiryPage()'> <span class='glyphicon glyphicon-th-list'></span> View my list </button>");
function openEnquiryPage() {
location.href = "EnquiryPage.aspx";
//get the list from the storage into the hidden field
//getListOfProperties();//not in use...
}
The list is stored in localstorage as Json, I can see the correct data in the text box on the page
var retrievedData = localStorage.getItem("propertyArray");
proplist2.value = retrievedData;
declared as follows in asp.net control
<asp:TextBox ID="TextBox1" runat="server" Text="initial"></asp:TextBox>
BUT in the hidden field, the data is always = ""
<asp:HiddenField ID="txtPropList" runat="server"></asp:HiddenField>
javascript to populate the hidden field...
function getListOfProperties() {
document.getElementById("body_content_txtPropList").value = retrievedData;
var proplist2 = document.getElementById("body_content_txtPropertyList");
proplist2.value = retrievedData;
}
when I debug the following lines in the code behind ...
Page.ClientScript.RegisterStartupScript(this.GetType(),"prop", "getListOfProperties();",true);
_propertyListJson = txtPropList.Value;
propertyListJson I always = “”
Thank-you in advance.!
If you want to use the hidden field then you should use
<%=txtPropList.ClientID%>
as on when you render the page and see it in inspect element server would render the different Id so it would not store the value in hidden field simply so it is feasible to use ClientID to create the static mode. But as on when you call the javascript function from the c# code then it would call the javascript function but it would not wait for it and execute the next line of code as on at that time the value is not store in hidden field so it would return the null value.
If you want then call the function of javascript on page load event and then click the button and retrieve the value it would successfully retrieve the value but i dont think that these would be the feasible code from my opinion
I suggest to create the WebAPI which would simply get the the data from the localstorage and perform the operation
And webAPI can be easily called from javascript using ajax call
I hope this would be helpful and answer is satisfactory 😊☺
Thank You ☺🙂

Unable to get value of input using ASP.NET

I'm trying to return some text which was inputted into a textbox element on my website. After entering some text into it I noticed that this didn't return data:
document.getElementById('myTextBox').text;
But this did:
document.getElementById('myTextBox').value;
EDIT: The javascript above was used client side to test what was being read, using .text returns an empty string which, when passed back to the server, did indeed show an empty string. .value contained my entered data but when I tried using .value server side the errors occurred.
However in my .cs class when I tried to add the following:
string myInput = myTextBox.Value;
I get an error message saying
"System.Web.UI.WebControls.TextBox doesn't contain a definition for
'Value'...".
The example I was referencing came from here: http://www.aspsnippets.com/Articles/Get-value-of-HTML-Input-TextBox-in-ASPNet-code-behind-using-C-and-VBNet.aspx
My textbox is declared like:
<asp:TextBox ID="myTextBox" runat="server"></asp:TextBox>
However when I try to change the TextBox element to an Input element I get an error saying "The type or namespace name 'Input' does not exist..."
How can I pass the data which was entered into my TextBox back to the server?
In the tutorial you are refering they have demonstared how to access the html input textbox value at server side. You are mixing a html control and a asp.net server control.
This represents a ASP.NET server control:-
<asp:TextBox ID="myTextBox" runat="server"></asp:TextBox>
and you can access its value at server side (.cs file) like this:-
string vaue = myTextBox.Text;
On the other hand the html input can be converted into a server control by adding the runat="server" attribute like this:-
<input type="text" id="txtName" name="Name" value="" />
In this case it is HtmlInputText and you need to access it value like this:-
string value = txtName.Value;
HTML elements e.g (input) are not accessible in your code behind. Asp.Net controls like the one you used can be accessed if you use the runat="server" attribute.
If you want to access yout Asp.Net textbox in your codebehind (.cs) you don't need javascript. Just use:
string value = this.myTextBox.Text
But, if you textbox is only a HTML input, than, you need to use some Javascript logic to get the value of the input and pass it to your .cs file.
For that, you have to do something like this:
Passing values from javascript to code behind in ASP.NET
Use:
string myInput = myTextBox.Text;
This give you all the text typed in the textbox
To get the text of your textbox for a javascript function :
function GetValueOfmyTextBox()
{
var myTB = document.getElementById('<%= myTextBox.ClientID %>');
alert(myTB.value);
}

Using telerik radgrid itemcommand with a radwindow to get initial data for InsertMode Dropdowns

I need some assistance with the telerik radgrid's itemcommand to get some information from a user adding a new record prior to opening the Grid in Insert mode. I have the itemcommand working to open a radwindow, present the user with a dropdown list of items to select from and a radbutton to select the value and close the radwindow, then this value is passed back to the parent page in javascript. All the values are passed down and I can use the alert function to validate this.
So at this point I need to continue the flow to open the radgrid in insert mode and filter a dropdown in the insertmode using the value from the radwindow noted above. In order to use this value I'm attempting to assign it to a hidden radtextbox for use in the ItemDatabound event when the form is loading in insert mode. Unfortunately, the value isn't being set via the javascript in this hidden control and is acting like it is erroring somewhere in the javascript. I feel like I'm overcomplicating this but was hoping for some guidance on what others have done to implement something like this.
<asp:LinkButton ID="addNewRecord" runat="server" Text="Add New Record" OnClientClick="openWin(); return false;" OnClick="InitInsert">Add New Record</asp:LinkButton>
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
<script type="text/javascript">
//<![CDATA[
function openWin(sender, args) {
var oWnd = radopen("ParserFileNewDialog.aspx", "RadWindow1");
}
function OnClientClose(oWnd, args) {
//get the transferred arguments
var arg = args.get_argument();
if (arg) {
var lenderid = arg.LenderID;
var tb = null;
tb = $find("<%=newLenderID2.ClientID %>");
alert(tb.get_text());
tb.set_text(lenderid);
$find("<%=hdnInsertBtn2.ClientID %>").click();
}
}
//]]>
</script>
</telerik:RadCodeBlock>
Any help is greatly appreciated!
What type of control is the newLenderID2 that you attempt to set a value to? With this syntax, it should be a RadTextBox. If it is an asp:HiddenFiel, you need
$get("<%=newLenderID2.ClientID %>").value = lenderid;
If you get an error - what is the error?
Also, you can fire a grid command and pass an argument to it (depending on the command) directly via the grid's masterTableView client-side API and the fireCommand() method: http://www.telerik.com/help/aspnet-ajax/grid-gridtableview-firecommand.html. Thus, you may not need the hidden button at all. A hidden field will suffice for data transmission.

Set Text property of asp:label in Javascript PROPER way

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.
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 .
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.:';
}
}
Use the following code
<span id="sptext" runat="server"></span>
Java Script
document.getElementById('<%=sptext'%>).innerHTML='change text';
C#
sptext.innerHTML
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" />
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 :)
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!
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.

Categories