Does the ListBox SelectedIndexChanged event require postback in ASP.NET?
I'm trying to add a JavaScript function to show all selected items from a ListBox as concatentated strings in a Label on the page. It's needed because AutoPostBack="true" will cause the ListBox to scroll all the way back to the first selected item.
So 开发者_运维知识库this code works:
<script type="text/javascript">
function Updatelist() {
var sel = document.getElementById('<%=lstbxStuff.ClientID%>');
var lbl = document.getElementById('ctl00_cph_lblSelectedStuff');
var listLength = sel.options.length;
var textForListbox = "";
var list2length = 0;
for (var i = 0; i < listLength; i++) {
if (sel.options[i].selected) {
if(list2length == 0) {
textForListbox = sel.options[i].text;
} else {
textForListbox = textForListbox + ", " + sel.options[i].text;
}
list2length++;
}
}
lbl.innerText=textForListbox;
return textForListbox;
}
</script>
Unfortunately I still need the code behind SelectedIndexChanged delegate. Is there a way to use both of these without doing a PostBack? When I set AutoPostBack="false", my delegate never seems to be reached.
If you want to call a server side deligate then you have to do a PostBack.
What is the code on the server that needs to be ran? You should be able to do all the work in JavaScript, then have a different trigger (not selectedIndexChange) to run the server side code once all the list items are selected.
Have you also seen, Ajax UpdatePanel and maintainScrollPositionOnPostBack="true" so that the page retains it's scroll position after postbacks. However this will only affect the pages scroll bar not the selectbox.
I don't think AutoPostBack is the way to go for you if that isn't the behaviour you want. When ASP.Net does a full post back, it is the same as the "traditional" HTML form post, sending the whole content of the form back to ther server and waiting for a response (which happens to be the same page because of how Asp.Net responds). Hence why position in the listbox is lost - it's a brand new listbox you're getting back.
Have you looked at ASP.Net Ajax (UpdatePanels) as one possible option? This will behave the same as a postback in that it'll send data back to the server and call your methods, but only posts back part of the page.
精彩评论