Pass selected value server side dropdown list to javascript function - javascript

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.

Related

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 ☺🙂

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.

Pass Session Variable to another page Javascript

I guys, I'm creating a VB.NET application, and this is the first time that I used Session Variables.
What I want to do is to pass the session variable from a page (first.aspx) to another page (second.aspx) via url.
Here an example of what I want to do:
In the first.aspx.vb page I declare a session variable and assign to it a value
Session("example") = "example123"
Then I pass this Session Variable to the first.aspx page
Response.Write(Session("example"))
and via javascript read the value of the Variable
<script type= text/javascript>
var SessionVar = '<%=Session("example")%>)';
</script>
Now, what I want to do is to change the value of the Variable (for example setting it as example456), and then pass the variable to the second.aspx [for example with window.open()] so that the url not contains the value of the variable but its name:
url/second.aspx?value=example AND NOT url/second.aspx?value=example456
Infact I don't want that the user read the value of the variable.
Finally I have to read the value of the session variable in the second.aspx.vb via Request.QueryString("value") and do the various operations.
Is it possible ?
If not, there is anothe way to do this
Thanks for the help :)
To set session variable from javascript can be done like below:
Create a hidden field control on the first page
<asp:HiddenField ID="HiddenField1" runat="server" />
Client script to set value of the hidden field
function setVal(value) {
// if using jQuery
$("#<%= HiddenField1.ClientID%>").val(value);
// if using javascript
var hf = document.getElementById("<%= HiddenField1.ClientID%>");
hf.value = value;
}
Create a button or link to navigate to the second page
<asp:Button ID="Button1" runat="server" Text="Go to second page" OnClick="NavigateToSecondPage" />
or
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="NavigateToSecondPage">Go to second page</asp:LinkButton>
In the first page code behind, create the NavigateToSecondPage sub to handle the onclick event of the button/link
Protected Sub NavigateToSecondPage(sender As Object, e As EventArgs)
Session("example") = HiddenField1.Value
Response.Redirect("SecondPage.aspx")
End Sub
Therefore, in your second page, you can access the Session("example") value and it will have a new value set by the client script in the first page.
Session variables are called this way because they are passed automatically from one page to the other within the same session, so you should just modify the value of the variable whenever you want and then access it again in the second page to find the value. You don't need to pass anything explicitely.

jquery to select a dropdown list control in asp.net

I am using ASP.net and have a dropdown control.
<asp:DropdownList runat="server" ID = "fieldReadOnlyContent" Enabled="false" class = "attribute"><asp:ListItem value = "0">False</asp:ListItem><asp:ListItem value = "1">True</asp:ListItem></asp:DropdownList>
I wanted to adjust the dropdown control via the clientside controls qith jquery. I get the value which it needs to be set to.
//d[3] will be either true or false.
$("#fieldReadOnlyContent").val(d[3]);
the above attempt didnt seem to set the item to properly enabled. HOw would i do this?
Try this:
$("#<%=fieldReadOnlyContent.ClientID%>").val(d[3]);
The item is not getting set because $("#fieldReadOnlyContent").val(d[3]); will check for the value.
For your case
if(d[3]=='false'){
$("#fieldReadOnlyContent").val('0');
}
else
{
$("#fieldReadOnlyContent").val('1');
}
fieldReadOnlyContent is not necessarily the ID given to the client-side HTML element.
You can use ClientIDMode="Static" server-side to control the client-side ID in .net4.0 (source), or <%= fieldReadOnlyContent.ClientID %> to inject the client id directly into the javascript otherwise.

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