0

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.

2
  • You will need to make an ajax call back to the server to allow it to store the index in session. Commented Dec 9, 2010 at 11:00
  • Or use a cookie instead. Commented Dec 9, 2010 at 11:08

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@webnoob - no problems. Sometimes the best solutions are the simplest ones. :)
and the ones we think of last most of the time :)
1

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();
    }
});

Comments

0

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.

1 Comment

You can set a server side variable. It's controlling when it is set that is the issue ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.