0

I am trying to create a link, which will onclick change a session variable like this


<a href="/Index" onclick="<% HttpContext.Current.Session["location"] = location;%>" >
    <%=location%>
</a>

However, during processing the page the session changes on its own during generating each anchor element (with this onclick attribute). So I would like to create a javascript function like


<script type="text/javascript" >
    function session(location) {
        HttpContext.Current.Session["location"] = location;
    }
</script>

Unfortunatelly, I don't know enough, so this doesn't seem working.. Any ideas? Thanks in advance

1
  • Just to be clear, you want to change an ASP.NET variable when someone clicks on a link on the page? Commented Jul 30, 2009 at 8:26

2 Answers 2

2

Carefully read through this thread: How is ASP.NET and Javascript related?.

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

Comments

2

Session is an ASP.NET server object that is not accessible from the client through JavaScript directly (Session may be stored as a cookie on the client, but then even then, it is not designed to be accessed from the client-side directly). You could handle what you want to do in a number of ways -

  1. Store a value in a hidden input when a link is clicked and then read that value server-side and store in Session.

  2. Store in Session on postback in a Click event handler for the anchor. You may want to use the asp:HtmlAnchor control for this and set up an event handler for the OnServerClick event

2 Comments

I am sorry, but could you please be more specific (maybe with a small example)? I am still quite new to web development and after another hour trying I am still where I was before. I am using the asp.net mvc framework, so I would be rather interested in the second option, since I don't want to create an extra action accepting HttpVerbs.Post for each action. Or maybe I am completely lost in here..
I'm not overly familiar with how the ASP.NET MVC framework operates and my answer was based on ASP.NET webforms. I am more than happy for someone to edit the post to include an MVC example. In the meantime, i'll see if I can find a resource to update my answer with.

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.