I have web form and JavaScript function like this:
web form
<div>
<asp:DropDownList runat="server" ID="ddlType">
<asp:ListItem Value="1" Text="Type1"></asp:ListItem>
<asp:ListItem Value="2" Text="Type2"></asp:ListItem>
</asp:DropDownList>
<asp:LinkButton ID="lnkTest" OnClientClick='<%= "getValue('0' + '|' + 'ddlType.SelectedValue');return false;" %>' runat="server" Text="text">
new
</asp:LinkButton>
</div>
JavaScript function
<script>
function getValue(Input) {
var result = Input.split("|");
section1 = result[0];
section2 = result[1];
}
</script>
I need to pass string includes '0' (hardcoded) and ddlType.SelectedValue to getValue.
This web form has syntax error Server tags cannot contain <% ... %> constructs (I know). I can get selected value by getElementById but I want to pass SelectedValue as argument. I read many posts but none of them don't pass SelectedValue.
It would be very helpful if someone could explain solution for this problem.
SelectedValue is a server-side value. It's available to the server-side code at page load (i.e. before the page is rendered to the user). In javascript it has no meaning at all, and isn't available at the time when a user clicks on the link.
If you want to get the selected value on the client side you can do something like this:
First get rid of the all the OnClientClick code from your LinkButton.
Second, write some javascript like this (at the bottom of the page, after all your HTML/ASP markup:
document.getElementById("<%=lnkTest.ClientID %>").addEventListener("click", function(event) {
event.preventDefault(); //stop default action of the link button, to allow script to execute
var selectedVal = document.getElementById("<%=ddlType.ClientID %>").value;
getValue('0|' + selectedVal);
});
This will cause the browser to listen for a user clicking on the button, and then run the JS function given. That function fetches the currently selected value of the dropdown (as selected in the browser - at this point the server has no idea what's selected because no postback has happened) and passes that selected value to your existing getValue function.
N.B. In case you're wondering, the reason I use the contruct <%=ddlType.ClientID %> is because ASP.NET dynamically creates the client-side ID of each element based on the structure of the server-side controls it lies within. So just relying directly on the server-side ID (e.g. "ddlType") will not reliably identify the element in the rendered DOM. .NET provides the ClientID value at runtime in order to allow us to access the generated ID.
I have a custom webpart that displays report data. It lives inside a tab control, and inside an update panel so the call back to refresh the report data is async.
On the server, I need to process some data and send back a value for later use. This variable just needs to SIT there and wait for user action, and then a client side javascript will use read the variable and based on the condition of the variable, this javascript will programmatically "click" the button in the update panel.
THE UPDATE PANEL AND REPORT VIEWER ON THE PAGE
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnUnload="UpdatePanel_Unload">
<ContentTemplate>
<asp:Button ID="btnSendHiddenField" runat="server" style="visibility: hidden; display: none;" OnClick="btnSendHiddenField_Click"/>
<rsweb:ReportViewer ID="ReportViewer1" runat="server"
Font-Names="Verdana" Font-Size="8pt" Height="383px"
InteractiveDeviceInfos="(Collection)" ProcessingMode="Remote"
WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt" Width="757px"
SizeToReportContent="True">
</rsweb:ReportViewer>
<asp:HiddenField ID= "hiddenCurrentObjectId" runat="server"/>
</ContentTemplate>
</asp:UpdatePanel>
THE SERVER CODE THAT PROCESSES THE DATA AND SENDS BACK THE VARIABLE. I HAVE OMITTED THE UNRELATED CODE.
Protected Sub btnSendHiddenField_Click(sender As Object, e As EventArgs) Handles btnSendHiddenField.Click
Dim parsedObjectId As String = ""
parsedObjectId = "1000"
hiddenCurrentObjectId.Value = parsedObjectId
End Sub
In my OnUnload code for the panel. Which has to be there or there to make some other things work in the WebPart. I borrowed this OnUnload code to overcome a previous issue.
MY ONUNLOAD FUNCTION
Protected Sub UpdatePanel_Unload(sender As Object, e As EventArgs)
Dim methodInfo As MethodInfo = GetType(ScriptManager).GetMethods(BindingFlags.NonPublic Or BindingFlags.Instance).Where(Function(i) i.Name.Equals("System.Web.UI.IScriptManagerInternal.RegisterUpdatePanel")).First()
methodInfo.Invoke(ScriptManager.GetCurrent(Page), New Object() {TryCast(sender, UpdatePanel)})
End Sub
End Class
THE PROBLEM
The value from the hidden field gets wiped out on the return trip. I think it is getting wiped on the OnUnload function call.
MY QUESTION
What can I do to preserve this hidden field value so the client side javascript can use it when another user generated event occurs?
If you are lossing the hidden field value then simplest way it to store it in a ViewState of any Session value.
You can get the value in js as:
function GetSessionValue()
{
var sessionValue = "<%=Session["ITEM"].ToString()%>";
}
I have an asp hidden Value field:
<asp:HiddenField Value="" ID="TitleViewerHiddenValue" OnValueChanged="TitleViewerHiddenValue_ValueChanged" />
I have a javascript event:
function setHiddenValue()
{
var x = document.getElementById('<%=TitleViewerHiddenValue.ClientID %>');
x.textcontent = "HELLO WORLD"; // I feel this is wrong
}
How do I fix the javascript function so i can set the value of the hidden field and trigger the OnValueChanged event on the server?
x.value
It's a form element, not a display element.
For triggering the change event, see How can I trigger an onchange event manually?
Though I think if you're doing all of this to trigger ASP's built in stuff, you're trying to build a house out of duct tape.
I have something that depending if it is clicked or unclicked will do something. The thing is, that i tried to do an onclick and it will not fire. Is there some other thing that is needed for selecting/unselecting a checkbox?
ASP:
<div id = "gridDiv">
Turn on/off some code:
<asp:Checkbox runat="server" name = "gridlock" id = "gridLockAttribute" />
</div>
ClientSide:
$("#gridLockAttribute").click(function(){
try{
alert("test");
}catch(err){
}
});
It doesnt seem to alert.
ASP.NET may be name-mangling your ID if the control is within another control, so things like $("#gridLockAttribute") won't work. You have to use either:
$("#<%= gridLockAttribute.ClientID %>")
Or:
$('[id$=gridLockAttribute]')
I'd prefer the first method.
Furthermore, if you are trying to get the checkbox to cause a postback automatically, you'll need to set the AutoPostBack attribute on the checkbox to True.
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.