Reputation: 15934
When a user select a tab on my site, I would like to store which tab they are on so that I can send them back there after the page refreshes. I have this at the moment (excuse the bad coding atm, I am testing the concept):
$("#index_0_li").click(function() {
<%= Session["SelectedIndex"] = "0" %>
});
$("#index_1_li").click(function() {
<%= Session["SelectedIndex"] = "1" %>
});
var index = <%= Session["SelectedIndex"] %>;
The problem is, because <%= %>
doesn't wait for the on click, the index is always being set to 1.
Does anyone have any ideas on how I can achieve what I am trying to do?
Thanks.
Upvotes: 0
Views: 6816
Reputation: 10411
As El Ronnoco said, if you want the selected tab in the ASP.NET Session, then you need to send it back to the server. You could do this with an AJAX call, or you could include it with another post you do in your application.
However, if you simply want to maintain the selected tab for the client, you can do as RPM1984 suggested and store it in a cookie (or other local storage if HTML5 is allowed) and select that the tab last recorded in cookie/local storage upon loading the page. The following is off the top of my head so might have syntax errors (I'd need to see your tab and other markup to do a working solution):
$("#index_0_li").click(function() {
localStorage.setItem('SelectedTab', '#index_0_li');
});
$("#index_1_li").click(function() {
localStorage.setItem('SelectedTab', '#index_1_li');
});
$(document).ready(function() {
var index = localStorage.getItem('SelectedTab');
if (index !== null) {
$(index).click();
}
});
Upvotes: 1
Reputation: 244
The click function is client side javascript. You cannot set a serverside variable on the client. You should set the selectedindex serverside, for example using a jquery post.
Upvotes: 0
Reputation: 73113
Just use client-side session - aka "cookies".
Set the cookie on the click event, then when you submit the page (or "post back"), this cookie will be sent with the HTTP request, allowing you to read it via Request.Cookies
.
Upvotes: 5