Get variable value from aspx and use it in code behind - javascript

I am having a little issue. I have a drop down list which can have multiple values selected. I did that by simply adding a $('#id').attr('multiple','multiple');
I know there is a simple way of accessing variable from code behind to aspx page but now i need the opposite thing, because when I multiselect it, from the code file it doesn't recognize the multiselection but only takes 1 value. So basicly I was hoping for something like
var temp = $('#id').val(); --- It takes the selected items correctly
<% simplevariable= %> = temp;

You can add a HiddenField
<asp:HiddenField ID="hiddenField" runat="server" />
Set its value like
$("#<%=hiddenField.ClientID%>").val($('#id').val())
You can use HiddenField.Value in code behind

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

Pass selected value server side dropdown list to javascript function

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.

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.

How do I get a textbox with particular ValidationGroup in jQuery?

I have an ASP.NET TextBox ID="txtDate" in my usercontrol. It has ValidationGroup="MyUC" set. Now my UC is inside a Repeater Control. So there will be multiple instances of the same textbox.
I am able to get all textboxes like: $("[id$='_txtDate']");
Each of the txtDate will have a separate ValidationGroup assigned to it, dynamically.
So I want to get a textbox based on the id + ValidationGroup using jQuery / javascript.
How can it be done? Any guidance really appreciated.
Edited based on Josiah's Reply and the way I found:
Sorry, my scenario is kind of complicated to include entire code. In short the textboxes are attached to jquery datepicker and the code below runs when a date is selected. The same handler is attached to multiple textboxes. Here is what I have:
var valgrp="MyGroup"; /*this mygroup is dynamic but keeping static for e.g.*/
var txtdate1 = $("[id$='txtDate']").filter(function(){if(this.Validators!=null){return this.Validators[0].validationGroup == valgrp;}});
var txtdate2 = $("[id$='txtDate']").filter(function(){return this.validationGroup == valgrp;});
alert("date1- " + txtdate1.val()); /*this returns date selected from datepicker*/
alert("date2 " + txtdate2.val()); /*this returns empty*/
Depending on the date I want to do something else. So txtdate1 is currently working for me where I don't have to add class to my textbox. I was playing with the txtdate2 which isn't behaving how I was expecting and so I had to post this question.
Here is a sample test to see this.validationGroup not returned:
$(function () {
$("#btntest").click(function () {
$("[id$='txtDate']").each(function () {
alert(this.validationGroup);//returns undefined
alert(this.Validators[0].validationGroup); //returns "test"
});
});
});
<input id="btntest" type="button" value="button" />
<asp:TextBox ID="txtDate" runat="server" ValidationGroup="test"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Text="*" ErrorMessage="Required." ControlToValidate="txtDate" ValidationGroup="test"></asp:RequiredFieldValidator>
While Josiah's solution didn't work but his idea of attaching class to textbox could have been a potential solution. Since it didn't exactly fit my needs I would answer my own question. Here is the solution I came up with:
var valgrp="MyGroup"; /*this mygroup is dynamic but keeping static for e.g.*/
var txtdate1 = $("[id$='txtDate']").filter(function(){if(this.Validators!=null){return this.Validators[0].validationGroup == valgrp;}});
The above returns me the textbox I am looking for. The key is
this.Validators[0].validationGroup
It gets the validationGroup of the first validator control attached to the textbox (this).
From a few searches, the validation group is stored as a property on the Form Element.
So you can add a class selector like so:
$("[id$='_txtDate']").each(function(){
var group = this.validationGroup,
$this = $(this);
if(!$this.hasClass('validationgroup'))
$this.addClass('validationgroup ' + group);
});
Of course if you have a repeater you will need to run this code each time an row is repeated. But now you can select fields by validation group like this:
$('.validationgroup.[group name]')
I don't use jQuery, but I'd think it would be:
$("#txtDate[ValidationGroup='MyUc']")
since jQuery's selectors are based on CSS. That works with document.querySelector, unless having more that one element with the same id is causing problems.

Categories