I am trying to pass a JavaScript variable to a server-side tag to avoid a post-back.
I’d like the solution to look something like this:
Code Behind:
Public Property NameCollection As Dictionary(Of String, String)
JavaScript that I wish to have:
$('#<%= txtIDNumber.ClientID %>').change(function(){
var idNumber = $('#<%= txtIDNumber.ClientID %>').val();
var lblName = $('#<%= lblName.ClientID %>');
<%If NameCollection.ContainsKey(idNumber) Then %>
lblName.html('<%=NameCollection(idNumber)%>');
<%Else%>
lblName.html('<span class="error">Not a User</span>');
<%End If %>
});
These server-side tags work properly if I hard-code the idNumber (say ‘1234’ or something), so I know my object/code itself is working properly, but is there a way to get it to recognize/pass the JavaScript variable here?
Extra Info:
I do have a functional work-around, but it is the ugly and inefficient method of looping through all the items in the collection, so I would like to know how to do this better if there is a way to. Thanks for help. 🙂
EDIT FOR CLARIFICATION:
This is my current work-around. Very ugly because I can’t figure out a way to just use the idnumber as an index instead of looping through all items. The NameCollection is already loaded with the data on the ASP.NET page load event, so while I’m not sure what’s going on in the background with server-side tags, I assumed the data should exist in that object statically the way it was at the last call to the server, but that the snapshot of that data physically existed on the client-side (it would have to to avoid post-backs, right?)? Thus, I should be able to avoid having to talk to the server here since I am only accessing data that should already be on the client side? Correct me (nicely please) if I am wrong, since I’m not an expert on JavaScript or web programming in general and I have been able to find very few decent references on server-side tags.
$('#<%= txtIDNumber.ClientID %>').change(function(){
var idnumber = $('#<%= txtIDNumber.ClientID %>').val();
var lblName = $('#<%= lblName.ClientID %>');
var tempJSKey = '';
var tempJSValue = '<span class="error">Not a Member</span>';
<%If Not NameCollection Is Nothing Then%>
<%For Each kvp As System.Collections.Generic.KeyValuePair(Of String, String) In NameCollection %>
tempJSKey = '<%=kvp.Key %>';
if (tempJSKey == idnumber)
{
tempJSValue = '<%=kvp.Value%>';
}
<%Next%>
<%End If%>
lblName.html(tempJSValue);
});
The only way to do what you want here is with Ajax or forms.